Close

Servlet - HttpSessionListener use cases with example

[Last Updated: Jun 20, 2018]

HttpSessionListener can be used to get notified when a HTTP session is created and destroyed. For that we need to implement the methods; sessionCreated() and sessionDestroyed() respectively.

HttpSessionListener#sessionCreated() is invoked when a new session is created via HttpServletRequest#getSession() method.

HttpSessionListener#sessionDestroyed() is invoked either when:
session is invalidated by the use of HttpSession#invalidate()
or after some time of session timeout (the period during which no HTTP request has been made by the same client which this session belongs to). The servlet container at this point invalidates the session (after that HttpServletRequest#getSession(false) will return null).

When to use HttpSessionListener

HttpSessionListener#sessionCreated() should be used to customize session. For example we can use methods like HttpSession.setMaxInactiveInterval (sets timeout). It can also be used to set some generic session attributes by the use of HttpSession#setAttribute(). Generic in a sense that when sessionCreated() is invoked we don't have access to the HttpServletRequest instance, so we can only set some session attributes which should be used for all sessions regardless of the specific request. However we can access fully initialized HttpSession instance, including its session id.

HttpSessionListener#sessionDestroyed() should be used to release or clean up session specific resources. This method is invoked immediately when we call HttpSession#invalidate(). However, it is not invoked exactly the time when session expires (timeout has reached). 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 HttpSessionListener

package com.logicbig.example;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

@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(5);//in seconds
  }

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

A Servlet

@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 --");
          //todo populate some user objects in session

      }

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

Running

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

mvn tomcat7:run-war

Output

At server console:

-- creating new session in the servlet --
-- HttpSessionListener#sessionCreated invoked --
session id: BBA0AB8E79823A47A7459ACE7431531B
-- session created in the servlet --

After sometime of session expiration (5 seconds):

-- HttpSessionListener#sessionDestroyed invoked --

Example Project

Dependencies and Technologies Used:

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

HttpSessionListener Example Select All Download
  • servlet-detect-session-timeout
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • MySessionListener.java

    See Also