Spring MVC - Using HttpSession as Controller Method Argument [Updated: Apr 3, 2018, Created: Apr 3, 2018] |
|
||
If for some reasons we cannot use Session Scoped beans (last tutorial) then we have another option of working with low level Servlet API to maintain session attributes. In this example we are going to use Example@Controller @ResponseBody public class MyController { @RequestMapping(value = "/", produces = MediaType.TEXT_PLAIN_VALUE) public String handler(HttpSession httpSession) { String sessionKey = "firstAccessTime"; Object time = httpSession.getAttribute(sessionKey); if (time == null) { time = LocalDateTime.now(); httpSession.setAttribute(sessionKey, time); } return "first access time : " + time+"\nsession id: "+httpSession.getId(); } } OutputTo try examples, run embedded tomcat (configured in pom.xml of example project below): mvn tomcat7:run-war ![]() Refreshing above page multiple times will return the same output (including same session id) until the session expires. Example ProjectDependencies and Technologies Used:
|
|
||
|
|||
|
|||
|