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

14.7. Logging Messages Using a Servlet Context Event Listener

Problem

You want to log messages using log4j when a servlet context is created and shut down.

Solution

Use log4j and a servlet context event listener.

Discussion

The servlet API includes a listener interface named javax.servlet. ServletContextListener that you can use to notify a specific Java class when a servlet context is created or shut down. This notified class may want to log the servlet context creation or shut down or store an object attribute in the servlet context, actions that the Java class (the listener) takes when it receives its notification.

The servlet context listener is an application event listener, a category that also includes session event listeners (see Chapter 11 or Recipe 14.8) and request event listeners. For example, the session event listener receives notifications when the servlet container creates new HTTP session objects in order to track a user's progress through a web application. The servlet container notifies the request event listener when a user makes a web application request, so that a listener can take some kind of action—such as logging the user's IP address.

A javax.servlet.ServletContext is used to store attributes or access context parameters that are common to a web application, get RequestDispatcher objects for forwarding or including files (see Chapter 6), or get information such as an absolute pathname associated with a web resource. Every web application has one associated ...

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