Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

10.7 Recognizing Session Creation and Destruction

Classes that implement the ServletContextListener and ServletContext-AttributeListener interfaces respond to changes in the servlet context, which is shared by all servlets and JSP pages in the Web application. But, with session tracking (Section 2.10), data is stored in per-user HttpSession objects, not in the servlet context. What if you want to monitor changes to this user-specific data? That's the job of the HttpSessionListener and HttpSessionAttributeListener interfaces. This section discusses HttpSessionListener, the listener that is notified when a session is created or destroyed (either deliberately with invalidate or by timing out). Section 10.9 discusses HttpSessionAttributeListener, the listener that is notified when session attributes are added, replaced, or removed.

Using HttpSessionListener involves the following steps.

  1. Implement the HttpSessionListenerinterface. This interface is in the javax.servlet.httppackage.

  2. Override sessionCreatedand sessionDestroyed. The first of these (sessionCreated) is triggered when a new session is created. The second method (sessionDestroyed) is triggered when a a session is destroyed. This destruction could be due to an explicit call to the invalidatemethod or because the elapsed time since the last client access exceeds the session timeout.

  3. Obtain a reference to the session and possibly to the servlet context. Each of the two HttpSessionListenermethods takes an HttpSessionEventas an argument. The HttpSessionEvent class has a getSessionmethod that provides access to the session object. You almost always want this reference; you occasionally also want a reference to the servlet context. If so, first obtain the session object and then call getServletContexton it.

  4. Use the objects. Surprisingly, one of the only methods you usually call on the session object is the setAttributemethod. You do this in sessionCreatedif you want to guarantee that all sessions have a certain attribute. Wait! What about getAttribute? Nope; you don't use it. In sessionCreated, there is nothing in the session yet, so getAttributeis pointless. In addition, all attributes are removed before sessionDestroyedis called, so calling getAttributeis also pointless there. If you want to clean up attributes that are left in sessions that time out, you use the attributeRemovedmethod of HttpSessionAttributeListener(Section 10.9). Consequently, sessionDestroyedis mostly reserved for listeners that are simply keeping track of the number of sessions in use.

  5. Declare the listener. In the web.xml or TLD file, use the listener and listener-classelements to simply list the fully qualified name of the listener class, as below.

  • + Share This
  • 🔖 Save To Your Account