O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

11.10. Using a Listener to Monitor Session Attributes

Problem

You want a listener class to be notified when a session attribute is added, removed, or replaced.

Solution

Create a Java class that implements the HttpSessionAttributeListener interface. Register this class using the web application's deployment descriptor.

Discussion

The HttpSessionAttributeListener interface has three methods: attributeAdded( ) , attributeRemoved( ), and attributeReplaced( ) ; all have a parameter of the type HttpSessionBindingEvent. This listener is notified when the session sets, removes, or changes an attribute. Therefore, the method calls in the web application that cause an HttpSessionAttributeListener notification are:

  • HttpSession.setAttribute( String name,Object value ).

  • HttpSession.removeAttribute( String name ).

  • A call to HttpSession.setAttribute( ) when an attribute of the same name is already bound to the session. The original attribute is replaced, triggering a call to the attributeReplaced(HttpSessionBindingEvent event) method.

Example 11-16 displays a message to the console when a session object is bound, including the value of the object (which is a String in this simple example). Messages are also displayed when the attribute is removed or replaced. To make this listener available to the application:

  1. Give the class a zero-argument constructor.

  2. Add the class to the web application's WEB-INF/classes or lib directory (when it's in a JAR).

  3. Declare the listener in the deployment descriptor. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required