August 28, 2011

HttpSessionBindingListener Event Handler Implementation

The HttpSessionBindingListener interface is part of the Servlet API and lets us create an event-handler class that listens to events on an object that is bound to the session object as an attribute, namely, the binding and un-binding of the attribute object to the session.

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

1) Create an attribute class that implements the HttpSessionBindingListener interface methods, valueBound() and valueUnbound()

package info.icontraining.servlets;

import javax.servlet.http.*;

public class MyAttribute implements HttpSessionBindingListener {

   String id;
 
   public MyAttribute(String id) {
      this.id = id;
   }
 
   public String getId() {
      return this.id;
   }
 
   public void valueBound(HttpSessionBindingEvent hsbe) {
      HttpSession session = hsbe.getSession();
      System.out.println("Attribute added to session. Id = " + ((MyAttribute)hsbe.getValue()).getId());
   }

   public void valueUnbound(HttpSessionBindingEvent hsbe) {
      System.out.println("Attribute removed from session. Id = " + ((MyAttribute)hsbe.getValue()).getId());
   }
}

2) For the HttpSessionBindingListener class, configuration in the web.xml with the <listener> element is not required.

3) Create a servlet class that adds and removes the attribute to and from the session,

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("newAttr", new MyAttribute("20"));
        session.removeAttribute("newAttr");
   }
}

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