Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring mvc SpringWebMVC:将对象从处理程序拦截器传递到控制器?_Spring Mvc - Fatal编程技术网

Spring mvc SpringWebMVC:将对象从处理程序拦截器传递到控制器?

Spring mvc SpringWebMVC:将对象从处理程序拦截器传递到控制器?,spring-mvc,Spring Mvc,目前,我使用request.setAttribute()和request.getAttribute()将对象从处理程序拦截器传递到控制器方法。我不认为这是一种理想的技术,因为它要求我将HttpServletRequest作为控制器方法的参数。Spring在向控制器隐藏请求对象方面做得很好,所以除了这个目的,我不需要它 我尝试使用setAttribute()中设置的@RequestParam注释名称,但当然不起作用,因为请求属性不是请求参数。据我所知,没有@RequestAttribute注释可用

目前,我使用request.setAttribute()和request.getAttribute()将对象从处理程序拦截器传递到控制器方法。我不认为这是一种理想的技术,因为它要求我将HttpServletRequest作为控制器方法的参数。Spring在向控制器隐藏请求对象方面做得很好,所以除了这个目的,我不需要它

我尝试使用setAttribute()中设置的@RequestParam注释名称,但当然不起作用,因为请求属性不是请求参数。据我所知,没有@RequestAttribute注释可用于属性


我的问题是,有没有更好的方法将对象从拦截器转移到控制器方法,而不必将它们设置为请求对象的属性?

只是为了节省访问此页面的人的时间:因为Spring 4.3注释是Spring MVC的一部分,因此,无需创建自己的
@RequestAttribute
注释。

使用拦截器预处理方法和会话,如下所示:

拦截器:

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    if (!(handler instanceof HandlerMethod)) {
        return true;
    }
    HttpSession session = request.getSession();
    String attribute = "attribute";
    session.setAttribute("attributeToPass", attribute);
    return true;
}
控制器:

@RequestMapping(method = RequestMethod.GET)
public String get(HttpServletRequest request) {
    String attribute = (String)request.getSession().getAttribute("attribteToPass");
    return attribute;
}
示例使用:

拦截器
@组件
公共类ExampleRequestInterceptor
实现HandlerInterceptor{
@凌驾
公共布尔预处理(HttpServletRequest请求、HttpServletResponse响应、对象处理程序)引发异常{
//验证处理程序的逻辑、自定义逻辑等。
//为了举例说明,我在这里添加了一个“列表”,但是
//变量类型无关紧要。
列出您的属性=//定义您的属性变量
setAttribute(“yourAttribute”,yourAttribute);
返回true;
}
}
控制器
public ResponseEntity myControllerMethod(@RequestParam映射requestParams,@RequestAttribute列表yourAttribute){
//“yourAttribute”将在此处定义。
}

当控制器返回时,将其添加到会话中不会使spring在响应中将数据返回到客户端吗?