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 javax.servlet.http.HttpSession as a controller method argument. Spring supports this argument and it is never null. In the background, Spring uses HttpServletRequest#getSession() (check out ServletRequestMethodArgumentResolver #resolveArgument() method) which returns the session associated with the current request, or if the request does not have a session, a new session object is created.
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();
}
}
Output
To 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.