August 28, 2011

ServletContextAttributeListener Event Handler Implementation

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

The ServletContextAttributeEvent object that is passed as an argument to the 2 listener methods provides a handle to the ServletContext object and the name and value object of the attribute.

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

package info.icontraining.servlets.listeners;

import javax.servlet.*;

public class MyContextAttributeListener implements ServletContextAttributeListener {

   public void attributeAdded(ServletContextAttributeEvent scae) {
      System.out.println("New Context attribute added");
      ServletContext sc = scae.getServletContext();
      System.out.println("Name of Attribute added: " + scae.getName());
      System.out.println("Value of Attribute added: " + scae.getValue());

   public void attributeRemoved(ServletContextAttributeEvent scae) {
      System.out.println("Context attribute removed");
      System.out.println("Name of Attribute removed: " + scae.getName());
      System.out.println("Value of Attribute removed: " + scae.getValue());

   public void attributeReplaced(ServletContextAttributeEvent scae) {
      System.out.println("Context attribute replaced");
      System.out.println("Name of Attribute replaced: " + scae.getName());
      System.out.println("Value of Attribute replaced: " + scae.getValue());

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


3) Create a servlet class that adds, replaces and removes an attribute from the ServletContext

package info.icontraining.servlets;


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

public class ContextAttribute extends HttpServlet {

   public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
      ServletContext sc = getServletContext();
      sc.setAttribute("attr1", "value1");
      sc.setAttribute("attr1", "value2");

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


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


No comments:

Post a Comment