Close

Servlet - HttpSessionBindingListener use cases with example

[Last Updated: Jun 26, 2018]

HttpSessionBindingListener can be implemented by a class to get notified when its instance is added to the session or when it is removed from the session.

HttpSessionBindingListener#valueBound() is invoked when this object is added to the session by the use of HttpSession.setAttribute().

HttpSessionBindingListener#valueUnbound() is invoked when this object is removed from the session. That happens when

  • HttpSession.removeAttribute() is used for this object.
  • Or HttpSession#invalidate() is used.
  • Or after some time of session timeout.

When to use HttpSessionBindingListener

HttpSessionBindingListener#valueBound() should be used to initialize resources related to this object.

HttpSessionBindingListener#valueUnbound() should be used to clean up resources related to this object. Note that this method is invoked immediately when object is removed via HttpSession#removeAttribute() or when session is invalidated via HttpSession#invalidate(). However, it is not invoked exactly at the same time when session expires (timeout reaches). It is invoked after some time of session expiration, depending on the servlet container implementation. So in this method we should not apply some logic which should be invoked immediately at session expiration.

Example

Implementing HttpSessionBindingListener

@WebListener
public class UserData implements HttpSessionBindingListener {

  @Override
  public void valueBound(HttpSessionBindingEvent event) {
      System.out.println("-- HttpSessionBindingListener#valueBound() --");
      System.out.printf("added attribute name: %s, value:%s %n",
              event.getName(), event.getValue());
  }

  @Override
  public void valueUnbound(HttpSessionBindingEvent event) {
      System.out.println("-- HttpSessionBindingEvent#valueUnbound() --");
      System.out.printf("removed attribute name: %s, value:%s %n",
              event.getName(), event.getValue());
  }
}

Implementing HttpSessionListener

We are also implementing HttpSessionListener to set a session timeout value and also to print messages to see the relative lifecycle notification of the session itself.

@WebListener
public class MySessionListener implements HttpSessionListener {
  @Override
  public void sessionCreated(HttpSessionEvent se) {
      System.out.println("-- HttpSessionListener#sessionCreated invoked --");
      HttpSession session = se.getSession();
      System.out.println("session id: " + session.getId());
      session.setMaxInactiveInterval(60);//in seconds
  }

  @Override
  public void sessionDestroyed(HttpSessionEvent se) {
      System.out.println("-- HttpSessionListener#sessionDestroyed invoked --");
  }
}

Servlets

Following servlet initiates a session and add an instance of 'UserData' to it.

@WebServlet(name = "myServlet", urlPatterns = {"/"})
public class MyServlet extends HttpServlet {

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
          throws ServletException, IOException {

      HttpSession session = req.getSession(false);
      if (session == null) {
          System.out.println("-- creating new session in the servlet --");
          session = req.getSession(true);
          System.out.println("-- session created in the servlet --");
      }

      UserData userData = (UserData) session.getAttribute("userData");
      if (userData == null) {
          userData = new UserData();
          session.setAttribute("userData", userData);
      }

      resp.setContentType("text/html");
      PrintWriter w = resp.getWriter();
      w.write("Hello !!");
  }
}

Following servlet removes 'UserData' attribute from the session.

@WebServlet(name = "myServlet3", urlPatterns = {"/clean"})
public class MyServlet3 extends HttpServlet {

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
          throws IOException {

      HttpSession session = req.getSession(false);
      if (session != null && session.getAttribute("userData") != null) {
          System.out.println("-- removing userData attribute from session --");
          session.removeAttribute("userData");
      }

      resp.setContentType("text/html");
      PrintWriter w = resp.getWriter();
      w.write("attribute removed !!");
  }
}

Following servlet invalidates the session.

@WebServlet(name = "myServlet2", urlPatterns = {"/invalidate"})
public class MyServlet2 extends HttpServlet {

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
          throws IOException {

      HttpSession session = req.getSession(false);
      if (session != null) {
          System.out.println("-- invalidating session --");
          session.invalidate();
      }

      resp.setContentType("text/html");
      PrintWriter w = resp.getWriter();
      w.write("session invalidated !!");
  }
}

Running

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

mvn tomcat7:run-war

Output

Accessing http://localhost:8080/ from browser, prints the following on the console:

-- creating new session in the servlet --
-- HttpSessionListener#sessionCreated invoked --
session id: 56A239430222B1CBE8A8A5DDFB764AFD
-- session created in the servlet --
-- HttpSessionBindingListener#valueBound() --
added attribute name: userData, value:com.logicbig.example.UserData@4d7c522

http://localhost:8080/clean prints the following:

-- removing userData attribute from session --
-- HttpSessionBindingEvent#valueUnbound() --
removed attribute name: userData, value:com.logicbig.example.UserData@604a95c7

After accessing http://localhost:8080/ again to add the object back to the session and then http://localhost:8080/invalidate

-- invalidating session --
-- HttpSessionListener#sessionDestroyed invoked --
-- HttpSessionBindingEvent#valueUnbound() --
removed attribute name: userData, value:com.logicbig.example.UserData@24cce3f2

Access http://localhost:8080/ and wait till session timeouts:

-- HttpSessionListener#sessionDestroyed invoked --
-- HttpSessionBindingEvent#valueUnbound() --
removed attribute name: userData, value:com.logicbig.example.UserData@5b21392

Example Project

Dependencies and Technologies Used:

  • javax.servlet-api 3.1.0 Java Servlet API
  • JDK 1.8
  • Maven 3.5.4

HttpSessionBindingListener example Select All Download
  • servlet-http-session-binding-listener-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • UserData.java

    See Also