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.


Creating session scoped bean

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

Injecting session bean to Controller

public class MyController {
  private VisitorInfo visitorInfo;

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

  public String visitorHandler(String name) {
      return "redirect:/";

JSP pages


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


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


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
          • webapp
            • WEB-INF
              • views

    See Also