Close

Servlet - HttpSessionAttributeListener use cases with example

[Last Updated: Jun 26, 2018]

HttpSessionAttributeListener can be implemented to get notified when attributes to HttpSession are added or removed.

HttpSessionAttributeListener#attributeAdded() is invoked when an attribute added by the use of HttpSession.setAttribute().

HttpSessionAttributeListener#attributeReplaced() is invoked when an an existing attribute is replaced by the use of HttpSession.setAttribute()

HttpSessionAttributeListener#attributeRemoved() is invoked when an attribute is removed from the session. That happens when

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

HttpSessionAttributeListener vs HttpSessionBindingListener

HttpSessionAttributeListener is used to listen to all global attributes changes, whereas HttpSessionBindingListener (last example) is used to listen to a particular attribute. Also HttpSessionBindingListener has to be implemented by the attribute value class itself.

When to use HttpSessionAttributeListener

HttpSessionAttributeListener#attributeAdded() and HttpSessionAttributeListener#attributeReplaced() can be used to initialize resource related to the attribute objects, or it can be used to monitor the attributes.

HttpSessionAttributeListener#attributedRemoved() should be used to clean up resources related to the attribute object being removed. This method is invoked immediately when HttpSession#removeAttribute() is used 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 cannot apply some logic which should be invoked immediately at session expiration.

Example

Implementing HttpSessionAttributeListener

@WebListener
public class MySessionAttributeListener implements HttpSessionAttributeListener {
  @Override
  public void attributeAdded(HttpSessionBindingEvent event) {
      System.out.println("-- HttpSessionAttributeListener#attributeAdded() --");
      System.out.printf("added attribute name: %s, value:%s %n", event.getName(),
              event.getValue());
  }

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

  @Override
  public void attributeReplaced(HttpSessionBindingEvent event) {
      System.out.println("-- HttpSessionAttributeListener#attributeReplaced() --");
      System.out.printf("replaced 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 notifications 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 adds or replaces the attributes.

@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 --");
      }

      session.setAttribute("test-attribute-1", "test attribute value 1");
      session.setAttribute("test-attribute-2", "test attribute value 2");

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

Following servlet removes 'test-attribute-1' attribute.

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

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

      HttpSession session = req.getSession(true);
      System.out.println("-- removing attributes from session --");
      session.removeAttribute("test-attribute-1");

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

Following servlet invalidates the session.

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

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
          throws ServletException, 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: 70176505145FD04A5980116097F41A02
-- session created in the servlet --
-- HttpSessionAttributeListener#attributeAdded() --
added attribute name: test-attribute-1, value:test attribute value 1 
-- HttpSessionAttributeListener#attributeAdded() --
added attribute name: test-attribute-2, value:test attribute value 2

http://localhost:8080/removeAttribute prints the followings:

-- removing attributes from session --
-- HttpSessionAttributeListener#attributeRemoved() --
removed attribute name: test-attribute-1, value:test attribute value 1

Accessing http://localhost:8080/ again :

-- HttpSessionAttributeListener#attributeAdded() --
added attribute name: test-attribute-1, value:test attribute value 1 
-- HttpSessionAttributeListener#attributeReplaced() --
replaced attribute name: test-attribute-2, value:test attribute value 2

Accessing http://localhost:8080/invalidate:

-- invalidating session --
-- HttpSessionListener#sessionDestroyed invoked --
-- HttpSessionAttributeListener#attributeRemoved() --
removed attribute name: test-attribute-2, value:test attribute value 2 
-- HttpSessionAttributeListener#attributeRemoved() --
removed attribute name: test-attribute-1, value:test attribute value 1

Access http://localhost:8080/ again to add the attributes back to the session and then wait till session timeouts:

-- HttpSessionListener#sessionDestroyed invoked --
-- HttpSessionAttributeListener#attributeRemoved() --
removed attribute name: test-attribute-2, value:test attribute value 2 
-- HttpSessionAttributeListener#attributeRemoved() --
removed attribute name: test-attribute-1, value:test attribute value 1

Example Project

Dependencies and Technologies Used:

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

Servlet - HttpSessionAttributeListener example Select All Download
  • servlet-http-session-attribute-listener-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • MySessionAttributeListener.java

    See Also