Close

Spring MVC - Session Scoped Bean created via Class Based Proxy Example

[Last Updated: Apr 18, 2018]

The 'session' scoped bean lives within a HTTP Session. We already have seen an example of 'session' scoped bean by using JSR 330 Provider approach. In following example, we will create 'session' scoped bean by using class based proxy.

Example

Creating session scoped bean

@Component
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class VisitorInfo implements Serializable {
  private String name;
  private int visitCounter;
  private LocalDateTime firstVisitTime;
  //getters/setters
    .............
}

Injecting session bean to Controller

@Controller
public class MyController {
  @Autowired
  private VisitorInfo visitorInfo;

  @RequestMapping("/**")
  public String appHandler(Model model) {
      if (visitorInfo.getName() == null) {
          return "main";
      }
      model.addAttribute("visitor", visitorInfo);
      visitorInfo.increaseVisitorCounter();
      return "app-page";
  }

  @PostMapping("/visitor")
  public String visitorHandler(String name) {
      visitorInfo.setName(name);
      visitorInfo.setFirstVisitTime(LocalDateTime.now());
      return "redirect:/";
  }
}

JSP pages

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

<html>
<body>
<h3> Main page <h3>
<p>Enter visitor name</p>
<form action="/visitor" method="post" >
<pre>
                  Name <input type="text" name="name" />
                        <input type="submit" value="Submit" />
</pre>
</form>
</body>
</html>

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

<html>
<body>
<h3>App</h3>
<p>Visitor name: ${visitor.name}</p>
<p>Visit counts: ${visitor.visitCounter}</p>
<p>First Visit at: ${visitor.firstVisitTime}</p>
</body>
</html>

Output

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

mvn tomcat7:run-war

Accessing http://localhost:8080/

Accessing other URIs:

Visitor name and first access time is remembered through multiple requests and the visit counter increased gradually; that shows that a single VisitorInfo instance is used. A new instance of VisitorInfo will be created at the beginning of new Http Session.

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 Session Scope Using Proxy Example Select All Download
  • session-scope-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • VisitorInfo.java
          • webapp
            • WEB-INF
              • views

    See Also