Home > Articles > Programming > Java

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

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.

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

  2. 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.

  3. 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 attribute—the 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.

  4. 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).

  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