Spring 3 HandlerInterceptor将信息传递给Controller

时间:2016-09-21 13:59:13

标签: java spring

我已经设置了一个Spring HandlerInterceptor来向HttpServletRequest添加一个属性,以便能够从Controller读取它,遗憾的是这似乎不起作用,这对我来说似乎很奇怪。我做错了吗?知道如何将数据从拦截器传输到控制器吗?

以下是两个受影响的类的简化代码

public class RequestInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        request.setAttribute("my-role", "superman");
    }
   [...]
}

@RestController
@RequestMapping("Test")
public class TestController {
    public final Logger logger = LoggerFactory.getLogger(getClass());

    @RequestMapping(value = "something")
    public void something(HttpServletRequest request) {
        logger.info(request.getAttribute("my-role"));
    }

    [...]
}

request.getAttribute(“my-role”)返回null ...但如果我在HandlerInterceptor的postHandle中读取它,确实会返回例外值,我觉得我错过了什么......

编辑:我发现通过会话“request.getSession()。setAttribute”作为一个魅力,我仍然不明白为什么请求本身在这个用例中不起作用。

1 个答案:

答案 0 :(得分:2)

您可以尝试使用会话而不是下面的请求。

  public boolean preHandle(HttpServletRequest request,
                HttpServletResponse response, Object handler) throws Exception {
                ...
                HttpSession session = request.getSession();
                session.setAttribute("attributeName", objectYouWantToPassToHandler);
                ....
                }
    In your handler handleRequest method:

       public ModelAndView handleRequest(HttpServletRequest request,
            HttpServletResponse response) throws Exception {                

            ....
            HttpSession session = request.getSession();
            objectYouWantToPassToHandler objectYouWantToPassToHandler = session.getAttribute("attributeName");
            ....


  }