【问题标题】:Spring Web MVC: Pass an object from handler interceptor to controller?Spring Web MVC:将对象从处理程序拦截器传递到控制器?
【发布时间】:2010-09-27 17:26:38
【问题描述】:

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

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

我的问题是,有没有更好的方法可以将对象从拦截器传递给控制器​​方法,而无需将它们设置为请求对象的属性?

【问题讨论】:

    标签: spring-mvc


    【解决方案1】:

    像这样使用拦截器预处理方法和会话:

    拦截器:

    @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;
    }
    

    【讨论】:

    • 不把它添加到会话中使spring在控制器返回时在响应中将数据返回给客户端吗?
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      一个使用@RequestAttribute的例子:

      拦截器

      @Component
      public class ExampleRequestInterceptor
              implements HandlerInterceptor {
      
          @Override
          public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
              // Logic to verify handlers, you custom logic, etc.
      
              // Just for illustration, I'm adding a `List<String>` here, but
              // the variable type doesn't matter.
              List<String> yourAttribute = // Define your attribute variable
              request.setAttribute("yourAttribute", yourAttribute);
              return true;
          }
      }
      

      控制器

      public ResponseEntity<?> myControllerMethod(@RequestParam Map<String, String> requestParams, @RequestAttribute List<String> yourAttribute) {
          // `yourAttribute` will be defined here.
      }
      

      【讨论】:

        猜你喜欢
        • 2018-06-24
        • 2014-06-11
        • 1970-01-01
        • 1970-01-01
        • 2014-11-21
        • 1970-01-01
        • 2015-09-13
        • 1970-01-01
        • 2013-12-13
        相关资源
        最近更新 更多