Search code examples
javaspring-mvccontrollerhttpsessionrequest-mapping

Declare HttpSession globally at the Controller class?


I have 2 @RequestMapping in below Controller class, both having HttpSession httpSession.

Is it possible to declare HttpSession httpSession globally, so that i can declare HttpSession once and can be used in multiple functions?

@Controller
public class ControllerClass{

    @RequestMapping(value="/sectionsAjax", method=RequestMethod.POST)
    public @ResponseBody String sectionsAjax(HttpSession httpSession){
        // Code
    }

    @RequestMapping(value="loadAjax", method=RequestMethod.POST)
    public @ResponseBody String sectionsAjax(HttpSession httpSession){
        // Code
    }
}

Solution

  • Not running in the context of a request, you may have no HttpSession available. Even in the context of a request there may (yet) be no session created.

    What may fit in your case (although it is no better than your current approach) is using spring's RequestContextHolder.

    Something like

    public static HttpSession getHttpSession() {
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attr.getRequest().getSession(true);
    }
    

    will always work (after adding a check for getRequestAttributes not returning null) in a servlet container (creating a session, if there is none).

    To expand a bit, as you asked about injecting (or "globally declaring") the HttpSession into your controller. Spring's controllers (i.e. the underlying Java objects) are very long lived singleton objects, having so called "singleton scope". The session is an object of "session scope" so cannot directly be injected to the controller (a dependence has to be equally or longer living). One may use proxies (having in this case singleton scope) resolving values having e.g. session scope; but that's not worth the hassle in your case. For further info look at spring's very good reference, specifically at the chapter Bean scopes.