Getting HttpSession Object in Spring Controller is very easy . Just Put it as a method parameter in controller method and Spring will automatically inject it .
@RequestMapping(value = "/test", method = RequestMethod.POST) @ResponseBody public JsonResponse getSessionIncontroller (@RequestBody String jsonReqString ,HttpSession session) { session.setAttribute("success" , "successfully accessed"); return jsonResponse; }Access the session variable in jsp using EL like this :
<%@ page isELIgnored="false"%> <c:if test="${not empty success}"> <div id="success" class="success"> <c:out value="${success}"></c:out> </div> </c:if>Or , you can inject HttpServletRequest Object in controller method and get the session object from it
@RequestMapping(value = "/test", method = RequestMethod.POST) @ResponseBody public JsonResponse getSessionIncontroller (@RequestBody String jsonReqString ,HttpServletRequest request) { Session session = request.getSession(); session.setAttribute("success" , "successfully accessed"); return jsonResponse; }There is another approach where we create Session scoped Controller . This Controller get created for each session and controller object is stored in session.
@Controller @Scope("session") public class SessionScopedController { private Cart cart = new Cart(); @RequestMapping("/addToCart") public String addToCart(@RequestParam("id") int id) { } }Or , you can create a session scoped component and inject this in your controller like this :
@Component @Scope("session") public class Cart { // simple POJO fields }
@Controller @Scope("request") public class SessionController { @Autowired private Cart cart; @RequestMapping("/addToCart") public String addToCart(@RequestParam("id") int id) { // } }Please note that the scope of controller is request , so for every request a new controller is created and session variable cart is injected in this . Another method is to use Scoped Proxy like this :
@Component @Scope("session",proxyMode=ScopedProxyMode.INTERFACES) public class Cart { // simple POJO fields }
@Controller public class SessionController { @Autowired private Cart cart; @RequestMapping("/addToCart") public String addToCart(@RequestParam("id") int id) { // } }Now the controller need not be request scope. So the overhead of creating a controller for each request is removed , and we don't have to add HttpSession in each controller method either . The Scoped Proxy make sure to get the session each time it is accessed . Reference Post Comments And Suggestions !!