August 28, 2011

ServletRequestListener Event Handler Implementation

The ServletRequestListener interface is part of the Servlet API and lets us create an event-handler class that listens to events on the ServletRequest object, namely, the request object creation and destruction.

TheServletRequest Event object that is passed as an argument to the 2 listener methods provides a handle to the ServletRequest object.

1) Create a class that implements the ServletRequestListener interface methods, requestInitialized() and requestDestroyed()

package info.icontraining.servlets.listeners;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;

public class MyServletRequestListener implements ServletRequestListener{

   public void requestDestroyed(ServletRequestEvent sre) {
      System.out.println("Request serviced & object destroyed by container");
   }

   public void requestInitialized(ServletRequestEvent sre) {
      System.out.println("New Request received and object created");
      HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
      // do something when a new request arrives
   }
}
2) Configure the listener in the web.xml deployment descriptor,

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

3) Create a servlet class that handles a request,

package info.icontraining.servlets;

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

public class RequestListenerServlet extends HttpServlet {

   public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
      request.setAttribute("attr1", "value1");
      request.setAttribute("attr1", "value2");
      request.removeAttribute("attr1");
   }
}

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

<servlet>
   <servlet-name>requestListenerServlet </servlet-name>
   <servlet-class>info.icontraining.servlets.RequestListenerServlet </servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>requestListenerServlet </servlet-name>
   <url-pattern>/RequestListenerServlet </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/requestListenerServlet

No comments:

Post a Comment