August 28, 2011

HttpSessionListener Event Handler Implementation

The HttpSessionListener 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 HttpSession object creation and destruction.

The HttpSessionEvent object that is passed as an argument to the 2 listener methods provides a handle to the HttpSession object in order to set any attributes.

1) Create a class that implements the HttpSessionListener interface methods, sessionCreated() and sessionDestroyed()

package info.icontraining.servlets.listeners;

import javax.servlet.http.*;

public class MySessionListener implements HttpSessionListener {

   public void sessionCreated(HttpSessionEvent se) {
      System.out.println("Created new session with client");
      HttpSession session = se.getSession();
      System.out.println("Printing Session Id: " + session.getId());
   }

   public void sessionDestroyed(HttpSessionEvent se) {
      System.out.println("Session "+ se.getSession().getId() +" ended");
   }
}

2) Configure the listener in the web.xml deployment descriptor,

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

3) Create a servlet class that starts a 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.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