15

In short, I want something like:

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

instead of

public String action(HttpSession session) {
     User user = session.getAttribute("user");
}

Mainly for the sake of:

  • readability
  • unit testing
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140

3 Answers3

19

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.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • What if you have @SessionAttribute(required = false) User user. The default value that is returned as a string doesn't match with User. Can you manage that somehow? – mickthompson Jan 14 '11 at 16:01
4

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.

drew
  • 2,949
  • 3
  • 25
  • 27
0

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());

}