- Monitoring Creation and Destruction of the Servlet Context
- Example: Initializing Commonly Used Data
- Detecting Changes in Servlet Context Attributes
- Example: Monitoring Changes to Commonly Used Data
- Packaging Listeners with Tag Libraries
- Example: Packaging the Company Name Listeners
- Recognizing Session Creation and Destruction
- Example: A Listener That Counts Sessions
- Watching for Changes in Session Attributes
- Example: Monitoring Yacht Orders
- Using Multiple Cooperating Listeners
- The Complete Events Deployment Descriptor
10.9 Watching for Changes in Session Attributes
OK, so HttpSessionListener lets you detect when a session is created or destroyed. But, since session attributes are removed before session destruction, this listener does not let you clean up attributes that are in destroyed sessions. That's the job of the HttpSessionAttributeListener interface. Use of this interface involves the following steps.
Implement the HttpSessionAttributeListener interface. This interface is in the javax.servlet.httppackage.
Override attributeAdded, attributeReplaced, and attributeRemoved. The attributeAddedmethod is triggered when a new attribute is added to a session. When a new value is assigned to an existing session attribute, attributeAddedis triggered with the new value and attributeReplacedis triggered with the old value (i.e., the value being replaced). The attribute-Removedmethod is triggered when a session attribute is removed altogether. This removal can be due to an explicit programmer call to removeAttribute, but is more commonly due to the system removing all attributes of sessions that are about to be deleted because their timeout expired.
Obtain references to the attribute name, attribute value, session, and servlet context. Each of the three HttpSession-AttributeListenermethods takes an HttpSessionBinding-Eventas an argument. The HttpSessionBindingEventclass has three useful methods: getName(the name of the attribute that was changed), getValue(the value of the changed attributethe new value for attributeAddedand the previous value for attribute-Replacedand attributeRemoved), and getSession(the HttpSessionobject). If you also want access to the servlet context, first obtain the session and then call getServletContexton it.
Use the objects. The attribute name is usually compared to a stored name to see if it is the one you are monitoring. The attribute value is used in an application-specific manner. The session is usually used to read previously stored attributes (getAttribute) or to store new or changed attributes (setAttribute).
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.
<listener> <listener-class>somePackage.SomeListener</listener-class> </listener>