Spring Web MVC: pass object from handler interceptor to controller?

I am currently using request.setAttribute () and request.getAttribute () as a means of transferring an object from a handler interceptor to a controller method. I do not see this as an ideal technique because it requires me to accept the HttpServletRequest as an argument to my controller methods. Spring does a good job of hiding the request object from the controllers, so I don't need it except for this purpose.

I tried using the @RequestParam annotation with the name I set in setAttribute (), but of course this did not work because the request attributes are not request parameters. As far as I know, there is no @RequestAttribute annotation for attributes for attributes.

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

+3
source share
3 answers

I do not think so.

But you can collapse your @RequestAttribute annotation. See spring mvc @RequestAttribute annotation, similar to @RequestParam , for a similar question and source link.

0
source

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

0
source

:

:

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

Source: https://habr.com/ru/post/1766815/


All Articles