Close

Spring MVC - Using HttpSession as Controller Method Argument

[Last Updated: 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 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.

Example Project

Dependencies and Technologies Used:

  • spring-webmvc 5.0.5.RELEASE: Spring Web MVC.
  • javax.servlet-api 3.0.1 Java Servlet API
  • JDK 1.8
  • Maven 3.3.9

Spring Mvc Http Session Param Select All Download
  • http-session-param-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • MyController.java

    See Also