Search code examples
javaspringspring-mvchttpsession

How to inject a value from HttpSession instead of the session


When using spring MVC it's really easy to pass the HttpSession to a method by just adding HttpSession session to the signature of the method, and later you can do something like

Integer valueFromSession = (Integer) session.getAttribute("key1")
Integer anotherValueFromSession = (Integer) session.getAttribute("key2")

The problem that I'm having right now is that we need values from the session in a lot of different methods in a lot of different controllers, so my question is if it's possible to get the value from the session and automatically inject it to the method and therefore instead of:

@GetMapping("/something")
public String foo(HttpSession session) {
    Integer valueFromSession = (Integer) session.getAttribute("key1")
    Integer anotherValueFromSession = (Integer) session.getAttribute("key2")

    return someMethod(valueFromSession, anotherValueFromSession);
}

I can have:

@GetMapping("/something")
public String foo(HttpSessionData dataFromSession) {

    return someMethod(dataFromSession.getValue(), dataFromSession.getAnotherValue();
}

Where DataFromSession is a class that gets populated from the HttpSession. Is there a way to do this?


Solution

  • You can use @SessionAttribute with spring MVC, it will retrieve the existing attribute from session, more see here

    @GetMapping("/something")
    public String foo(@SessionAttribute("key1") Integer key1, @SessionAttribute("key2") Integer key2) {
        return someMethod(key1, key2);
    }