Close

Spring MVC - Using Session Scoped Beans

[Updated: Apr 4, 2018, Created: Feb 21, 2016]

A backing object can be autowired/injected to a Spring MVC controller with predefined scopes. These scopes are 'request', 'session' and 'application' scopes.

To understand how to use session scope object, let's see an example.

Example

To avoid narrower scope bean DI problem as we saw when injecting Prototype bean into a Singleton Bean, we will preferably use JSR 330 Provider approach. Here's a list of other solutions.

Registering a bean with session scope

@EnableWebMvc
@Configuration
@Import(MyViewConfig.class)
public class MyWebConfig {

  @Bean
  public TradeController tradeController () {
      return new TradeController();
  }

  @Bean
  @Scope(WebApplicationContext.SCOPE_SESSION)
  public Visitor visitor(HttpServletRequest request){
       return new Visitor(request.getRemoteAddr());
  }
}

Injecting the session bean

We are going to inject our session bean wrapped in Provider interface:

@Controller
@RequestMapping("/trades")
public class TradeController {

  @Autowired
  private Provider<Visitor> visitorProvider;

  @RequestMapping("/**")
  public String handleRequestById (Model model, HttpServletRequest request) {
      model.addAttribute("msg", "trades request, serving page " + request.getRequestURI());
      visitorProvider.get()
                     .addPageVisited(request.getRequestURI());
      return "traders-page";
  }
}

JSP page

src/main/webapp/WEB-INF/views/traders-page.jsp

<%@ page language="java"
    contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<body>
<h2>Trades </h2>
   <h3> Message : ${msg} <h3>
<br/>
<h4>Current visitor history</h4>
<p>ip : ${visitor.ip}:</p>
<c:forEach items="${visitor.pagesVisited}" var="page">
    <p>${page}</p>
</c:forEach>

</body>
</html>

How it works?

The factory method of @Configuration class, MyWebConfig#visitor, is called at the beginning of each new HTTP session.

The returned object from the factory method is stored in HTTPSession and is kept there till the session ends.

visitorProvider.get() returns the same instance for the same session.

Output

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war



The outputs shows that all visited urls are added to a single instance of our Visitor object, hence it is kept in the HttpSession object.

Other ways to handle session attributes

  • Using @SessionAttributes (example here).
  • Using HttpSession as a controller method argument (next tutorial).

Example Project

Dependencies and Technologies Used:

  • Spring Web MVC 5.0.5.RELEASE: Spring Web MVC.
  • Spring TestContext Framework 5.0.5.RELEASE: Spring TestContext Framework.
  • Java Servlet API 3.0.1
  • javax.servlet:jstl 1.2
  • javax.inject 1: The javax.inject API.
  • JUnit 4.12: JUnit is a unit testing framework for Java, created by Erich Gamma and Kent Beck.
  • JDK 1.8
  • Maven 3.3.9

Spring Session Scope Example Select All Download
  • spring-session-scoped-object
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • TradeController.java
          • webapp
            • WEB-INF
              • views

    See Also