Home > Articles

  • Print
  • + Share This
  • 💬 Discuss
This chapter is from the book

Servlet Event Listeners

The final topic to discuss in this chapter is Servlet event listeners. In many situations it is desirable to be notified of container-managed life cycle events. An easy example to think of is knowing when the container initializes a Web Application and when a Web Application is removed from use. Knowing this information is helpful because you may have code that relies on it, perhaps a database that needs to be loaded at startup and saved at shutdown. Another good example is keeping track of the number of concurrent clients using a Web Application. This functionality can be done with what you currently know of Servlets; however, it can much more easily be done using a listener that waits for a client to start a new session. The greater point being presented here is that a container can be used to notify a Web Application of important events, and Servlet event listeners are the mechanism.

All of the Servlet event listeners are defined by interfaces. There are event listener interfaces for all of the important events related to a Web Application and Servlets. In order to be notified of events, a custom class, which implements the correct listener interface, needs to be coded and the listener class needs to be deployed via web.xml. All of the Servlet event listeners will be mentioned now; however, a few of the event listeners will not make complete sense until the later chapters of the book. In general, all of the event listeners work the same way so this fact is fine as long as at least one good example is provided here.

The interfaces for event listeners correspond to request life cycle events, request attribute binding, Web Application life cycle events, Web Application attribute binding, session36 life cycle events, session attribute binding, and session serialization, and appear, respectively, as follows:

  • javax.servlet.ServletRequestListener

  • javax.servlet.ServletRequestAttributeListener

  • javax.servlet.ServletContextListener

  • javax.servlet.ServletContextAttributeListener

  • javax.servlet.http.HttpSessionListener

  • javax.servlet.http.HttpSessionAttributeListener

  • javax.servlet.http.HttpSessionAttributeListener

Use of each listener is intuitive given an implementation of one and an example deployment descriptor. All of the listener interfaces define events for either the creation and destruction of an object or for notification of the binding or unbinding of an object to a particular scope.

As an example, let us create a listener that tracks the number of concurrent users. We could create a simple hit counter, by tracking how many requests are created; however, the previous hit counter examples in this chapter do a fine job providing the same functionality. Tracking the number of concurrent users is something that we have yet to see, and allows the introduction of session scope. For now, think of sessions as being created only once per unique client—regardless if the same person visits the site more than once. This is different from requests, which are created every time a client requests a resource. The listener interface we are going to implement is HttpSessionListener. It provides notification of two events: session creation and session destruction. In order to keep track of concurrent users, we will keep a static count variable that will increase incrementally when a session is created and decrease when a session is destroyed.

The physical methods required by the HttpSessionListener interface are as follows:

  • void sessionCreated(HttpSessionEvent evt): The method invoked when a session is created by the container. This method will almost always be invoked only once per a unique client.

  • void sessionDestroyed(HttpSessionEvent evt): The method invoked when a session is destroyed by the container. This method will be invoked when a unique client's session times out—that is, after they fail to revisit the Web site for a given period of time, usually 15 minutes.

Listing 2-20 provides our listener class's code, implementing the preceding two methods. Save the code as ConcurrentUserTracker.java in the /WEB-INF/classes/com/jspbook directory of the jspbook Web Application.

Listing 2-20. ConcurrentUserTracker.java

package com.jspbook;

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

public class ConcurrentUserTracker implements HttpSessionListener {
  static int users = 0;

  public void sessionCreated(HttpSessionEvent e) {
    users++;
  }
  public void sessionDestroyed(HttpSessionEvent e) {
    users--;
  }
  public static int getConcurrentUsers() {
    return users;
  }
}

The listener's methods are intuitive and the logic is simple. The class is trivial to create because the container is managing all the hard parts: handling HTTP requests, trying to keep a session, and keeping a timer in order to successfully time-out unused sessions.

Deploy the listener by adding the entry in Listing 2-21 to web.xml. Add the entry after the starting webapp element but before any Servlet deployments.

Listing 2-21. Deployment of the Concurrent User Listener

<listener>
  <listener-class>
   com.jspbook.ConcurrentUserTracker
  </listener-class>
</listener>

Notice that the deployment does not specify what type of listener interface is being used. This type of information is not needed because the container can figure it out; therefore, deployment of all the different listeners is similar to the above code. Create a listener element with a child listener-class element that has the name of the listener class.

One more addition is required before the concurrent user example can be tested. The concurrent user tracker currently doesn't output information about concurrent users! Let us create a Servlet that uses the static getConcurrentUsers() method to display the number of concurrent users. Save the code in Listing 2-22 as DisplayUsers.java in the /WEB-INF/com/jspbook directory of the jspbook Web Application.

Listing 2-22. DisplayUsers.java

package com.jspbook;

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

public class DisplayUsers extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
  throws IOException, ServletException {

    request.getSession();

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.print("Users:");
    out.print(ConcurrentUserTracker.getConcurrentUsers());
    out.println("</html>");
  }
}

Deploy the Servlet to the /DisplayUsers URL mapping. Compile both ConcurrentUserTracker.java and DisplayUser.java and reload the jspbook Web Application for the changes to take effect. Test the new functionality out by browsing to http://127.0.0.1/jspbook/DisplayUsers. An HTML page appears describing how many users are currently using the Web Application. A browser rendering would be provided; however, the page literally displays nothing more than the text "Users:" followed by the number of current users.

When browsing to the Servlet, it should say one user is currently using the Web Application. If you refresh the page, it will still say only one user is using the Web Application. Try opening a second Web browser and you should see that the page states two people are using the Web Application37. Upon closing your Web browser, the counter will not go down, but after not visiting the Web Application for 15 minutes, it will. You can test this out by opening two browsers (to create two concurrent users) and only using one of the browsers for the next 15 minutes. Eventually, the unused browser's session will time-out and the Web Application will report only one concurrent user. In real-world use, odds are that several independent people will be using a Web Application at any given time. In this situation you don't need to do anything but visit the DisplayUsers Servlet to see the current amount of concurrent users.

The concurrent user tracker is a handy piece of code; however, the greater point to realize is how Servlet event listeners can be coded and deployed for use. Event listeners in general are intuitive to use; the hard part is figuring out when and how they are best used, which is hard to fully explain in this chapter. In later chapters of the book, event listeners will be used to solve various problems and complement code. Keep an eye out for them.

  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus