Bozho Bozho - 1 year ago 108
Java Question

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download