O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

18.6. Counting the Number of Web Application Requests

Problem

You want to count the number of requests handled by a web application.

Solution

Use a javax.servlet.ServletRequestListener to be notified whenever an HTTP request is initialized.

Discussion

A request listener is a good candidate for tracking requests, because the web container notifies the listener of new requests by calling its requestInitialized( ) method. Example 18-8 keeps track of the request count with a static class variable named reqCount. The program increments this variable in a synchronized block within the requestInitialized( ) method.

The ServletContext is used to log a message about the request so that you can observe the listener behavior. However, a busy production application that logs information about every request typically represents an inefficient use of web container resources. This type of logging activity should be reserved for development applications.

Example 18-8. A request listener class for counting application requests

package com.jspservletcookbook;

import javax.servlet.*;
import javax.servlet.http.*;public class ReqListener implements ServletRequestListener {

    private static long reqCount;

  public void requestInitialized(ServletRequestEvent sre){ //used for logging purposes ServletContext context = sre.getServletContext( ); //Used to get information about a new request ServletRequest request = sre.getServletRequest( ); //The static class variable reqCount is incremented in this block; //the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required