August 28, 2011

ServletRequestAttributeListener Event Handler Implementation

The ServletRequestAttributeListener 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 addition, removal and replacement of attributes on the request object.

The ServletRequestAttributeEvent Event object that is passed as an argument to the listener methods provides a handle to the ServletRequest object and the name and value object of the attribute.

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

package info.icontraining.servlets.listeners;

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

public class MyRequestAttributeListener implements ServletRequestAttributeListener {

   public void attributeAdded(ServletRequestAttributeEvent srae) {
      System.out.println("New request attribute added");
      HttpServletRequest request = (HttpServletRequest) srae.getServletRequest();
      System.out.println("Name of Attribute added: " + srae.getName());
      System.out.println("Value of Attribute added: " + srae.getValue());
   }

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

   public void attributeReplaced(ServletRequestAttributeEvent srae) {
      System.out.println("Request attribute Replaced");
      System.out.println("Name of Attribute replaced: " + srae.getName());
      System.out.println("Value of Attribute replaced: " + srae.getValue());
   }
}

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

<listener>
   <listener-class>    
      info.icontraining.servlets.listeners.MyRequestAttributeListener
   </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