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.http package.

2.
Override attributeAdded, attributeReplaced, and attributeRemoved. The attributeAdded method is triggered when a new attribute is added to a session. When a new value is assigned to an existing session attribute, attributeAdded is triggered with the new value and attributeReplaced is triggered with the old value (i.e., the value being replaced). The attributeRemoved method 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 remov-ing 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 HttpSessionAttributeListener methods takes an HttpSessionBindingEvent as an argument. The HttpSessionBindingEvent class has three useful methods: getName (the name of the attribute that was changed), getValue (the value of the changed attribute—the new value for attributeAdded and the previous value for attributeReplaced and attributeRemoved), and getSession (the HttpSession object). If you also want access to the servlet context, first obtain the session and then call getServletContext on 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-class elements to simply list the fully qualified name of the listener class, as below.

<listener> 
  <listener-class>somePackage.SomeListener</listener-class> 
</listener> 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.165.115