简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM