开发者

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

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.

开发者_StackOverflow中文版

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?


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


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.


An example using @RequestAttribute:

Interceptor

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

Controller

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜