Listeners

Servlet event listeners allow programer to take some action when events related to Context and Session take place.

For example, you may want to know how many sessions are currently running. For this you need to increment a counter when a new session is created and decrement it when a session is terminated. This is possible only if you are notified when these events occur.

Servlets 2.3 onwards Listeners are provided for this purpose.

Thses listeners are provided as Interfaces. Interfaces are available for all important events related to Web application, Sessions and Request.

To understand how to create a listener and use it, let us create an appliction in Tomcat 4.x with the following directory structure.

c:\tomcat
  |
  |
   ---webapps
         |
         |
          ---- test
                |
	        |
                |---- WEB-INF
                |       |
		|	|
          	|	---classes
          	|	|  |
	        |       |  |
                |       |  ------- st
                |       -- web.xml |
	   	|                   |
                 -- usercount.jsp   ---- UserCountListener.java

Creating a Listener

In order to handle events of interest, you have to do two things: Now, let us see a simple example related to listener that handles session and context realted events. The class is called UserCountListner and it is implementing two listeners - ServletContextListner and HttpSessionListener.
package st;

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

public class  UserCountListener  implements ServletContextListener, HttpSessionListener
{

ServletContext sc;
int counter=0;

public void contextInitialized(ServletContextEvent sce)
{
  sc = sce.getServletContext();
  sc.setAttribute(("uc"),Integer.toString(counter));
}

public void contextDestroyed(ServletContextEvent sce) { }


public void sessionCreated(HttpSessionEvent hse)
{
  incrementUserCounter();
}

public void sessionDestroyed(HttpSessionEvent hse)
{
  decrementUserCounter();
}


synchronized void incrementUserCounter()
{
 counter = Integer.parseInt( (String)sc.getAttribute("uc"));
 counter++;
 sc.setAttribute(("uc"), Integer.toString(counter));
}

synchronized void decrementUserCounter()
{
  int counter = Integer.parseInt( (String)sc.getAttribute("uc"));

  counter --;
  sc.setAttribute(("uc"), Integer.toString(counter));
}
} // end of class

The class must be placed inside WEB-INF/classes/st directory as it belongs to st package.

Get into st directory and do the following.

  1. Set path and classpath as follows:
    path=c:\jdk1.5.0\bin
    set classpath=.;c:\tomcat\common\lib\servlet.jar
    
  2. Compile UserCountListner.java as follows:
    javac  UserCountListener.java
    

Deploying the listener

Once a listner class is created and compiled then it is to be deployed using web.xml as follows:
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

    <!-- Define example application and  session events listeners -->
    <listener>
        <listener-class>st.UserCountListener</listener-class>
    </listener>
    
</web-app>

Create a JSP which displays application attribute uc created in contextInitialized method and modified accordingly in sessionCreated and sessionDestroyed methods.

<html>
<body>
<h3>
No. Of Users : <%= application.getAttribute("uc").toString() %>
</h3>
</body>
</html>  

Make sure you start tomcat. Then execute the usercount.jsp as follows to see the effect of listener.

http://localhost:8080/test/usercount.jsp
If you run the same url from multiple instances of browser then you see count increasing. Try see what happens if you close some of the instances of browser!

The following are the other important interfaces realted to listeners.

Keep Learning,

P.Srikanth