Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 559
Bozho Avatar asked Sep 01 '10 19:09

Bozho


2 Answers

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.

like image 98
Bozho Avatar answered Nov 16 '22 07:11

Bozho


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.

like image 4
drew Avatar answered Nov 16 '22 07:11

drew