Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Web MVC: Pass an object from handler interceptor to controller?

Tags:

spring-mvc

Currently I am using request.setAttribute() and request.getAttribute() as a means to pass an object from a handler interceptor to a controller method. I don't view this as an ideal technique, because it requires that I take HttpServletRequest as an argument to my controller methods. Spring does a good job hiding the request object from controllers, so I would not need it except for this purpose.

I tried using the @RequestParam annotation with the name I set in setAttribute(), but of course that did not work because request attributes are not request params. To my knowledge, there is no @RequestAttribute annotation to use for attributes.

My question is, is there some better way to hand off objects from interceptors to controller methods without resorting to setting them as attributes on the request object?

like image 347
JamesH Avatar asked Sep 27 '10 17:09

JamesH


2 Answers

Use the interceptor prehandle method and session like this:

Interceptor:

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

Controller:

@RequestMapping(method = RequestMethod.GET)
public String get(HttpServletRequest request) {
    String attribute = (String)request.getSession().getAttribute("attribteToPass");
    return attribute;
}
like image 143
Cristian Rodriguez Avatar answered Oct 22 '22 00:10

Cristian Rodriguez


Just to save time for those visiting this page: since Spring 4.3 @RequestAttribute annotation is a part of Spring MVC, so there is no need to create your own @RequestAttribute annotation.

like image 23
Dawid Pytel Avatar answered Oct 22 '22 02:10

Dawid Pytel