How to pass a session attribute as method argument (parameter) with Spring MVC

前端 未结 3 1370
渐次进展
渐次进展 2020-12-03 01:30

In short, I want something like:

public String action(@SessionAttribute User user) {..}

instead of

public String action(Htt         


        
相关标签:
3条回答
  • 2020-12-03 02:10

    Even if we use @ModelAttribute("user") User user as the method parameter and then use user object in your method it will have updated user from session. The attribute name has to match with the session attribute name "user".

    public String myMethod( @ModelAttribute("user") User user ){
    
     System.out.println(user.getDetails());
    
    }
    
    0 讨论(0)
  • 2020-12-03 02:21

    I found a solution.

    The idea is to register a custom WebArgumentResolver for the AnnotationMethodHandlerAdapter, which handles a custom annotation - @SessionAttribute (or @SessionParam).

    One note to the code posted there is that param.getParameterName() can be used if no value is specified.

    0 讨论(0)
  • 2020-12-03 02:26

    For those arriving via Google, as of at least 4.3.2.RELEASE, Spring includes a @SessionAttribute annotation built-in:

    public String action(
        @SessionAttribute(required=false, name="user") User user) {
    
        // ...
    
    }
    

    A custom solution is no longer necessary.

    0 讨论(0)
提交回复
热议问题