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
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.
path=c:\jdk1.5.0\bin set classpath=.;c:\tomcat\common\lib\servlet.jar
javac UserCountListener.java
<?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.jspIf 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.