August 28, 2011

HttpSessionAttributeListener Event Handler Implementation

The HttpSessionAttributeListener interface is part of the Servlet API and lets us create an event-handler class that listens to events on the HttpSession object, namely, the addition, removed and replacement of attributes on the HttpSession object.

The HttpSessionBindingEvent object that is passed as an argument to the 2 listener methods provides a handle to the HttpSession object as well as access to the name and value object of the attribute.

1) Create a class that implements the HttpSessionAttributeListener interface methods, attributeAdded(), attributeRemoved() and attributeReplaced()

package info.icontraining.servlets.listeners;

import javax.servlet.http.*;

public class MySessionAttrListener implements HttpSessionAttributeListener {

   public void attributeAdded(HttpSessionBindingEvent hsbe) {
      System.out.println("New Session attribute added");
      HttpSession session = hsbe.getSession();
      System.out.println("Name of Attribute added: " + hsbe.getName());
      System.out.println("Value of Attribute added: " + hsbe.getValue());
   }

   public void attributeRemoved(HttpSessionBindingEvent hsbe) {
      System.out.println("Session attribute Removed");
      System.out.println("Name of Attribute removed: " + hsbe.getName());
      System.out.println("Value of Attribute removed: " + hsbe.getValue());
   }

   public void attributeReplaced(HttpSessionBindingEvent hsbe) {
      System.out.println("Session attribute replaced");
      System.out.println("Name of Attribute replaced: " + hsbe.getName());
      System.out.println("Value of Attribute replaced: " + hsbe.getValue());
   } 
}
2) Configure the listener in the web.xml deployment descriptor,

<listener>
   <listener-class>    
      info.icontraining.servlets.listeners.MySessionAttrListener
   </listener-class>
</listener>

3) Create a servlet class that starts a session and adds, replaces and removes a session attribute,

package info.icontraining.servlets;

import java.io.*;
import javax.servlet.http.*;

public class SessionServlet extends HttpServlet {

   public void doGet(HttpServletRequest request, HttpServletResponse response)  
   throws IOException {

      HttpSession session = request.getSession();
      session.setAttribute("attr1", "value1");
      session.setAttribute("attr1", "value2");
      session.removeAttribute("attr1");
      session.invalidate();
   }
}

4) Configure the servlet in the web.xml deployment descriptor,

<servlet>
   <servlet-name>sessionServlet</servlet-name>
   <servlet-class>info.icontraining.servlets.SessionServlet</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>sessionServlet</servlet-name>
   <url-pattern>/sessionServlet</url-pattern>
</servlet-mapping>

5) Test the example with the following URL in the browser, and check the server/console log

http://localhost:8080/WebAppName/sessionServlet

No comments:

Post a Comment