JavaCupiX JavaCupiX - 2 months ago 15
Java Question

Spring 3 HandlerInterceptor passing information to Controller

I've setup a Spring HandlerInterceptor to add an attribute to the HttpServletRequest to be able to read it from the Controller, sadly this does not seem to work which seems strange to me. Am I doing things wrong? Any idea how to transmit the data from the Interceptor to the Controller?

Here is the simplified code of the two impacted classes

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"));
}

[...]
}


The request.getAttribute("my-role") returns null... but does return the excepted value if I read it in the postHandle of the HandlerInterceptor, I feel like I'm missing something...

EDIT : I found out that going thru the session with "request.getSession().setAttribute" works as a charm, still i do not understand why the request itself does not work in this use case.

Answer

Can you try with session instead of request like below.

  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");
            ....


  }
Comments