Java, Programming

Servlet Life Cycle

The life cycle of a servlet is controlled by the container in which the servlet has been deployed. When a request is mapped to a servlet, the container performs the following steps.

  1. If an instance of the servlet does not exist, the Web container
    1. Loads the servlet class.
    2. Creates an instance of the servlet class.
    3. Initializes the servlet instance by calling the init method. Initialization is covered in Initializing a Servlet.
  2. Invokes the service method, passing a request and response object. Service methods are discussed in the section Writing Service Methods.

If the container needs to remove the servlet, it finalizes the servlet by calling the servlet’s destroy method. Finalization is discussed in Finalizing a Servlet.

Handling Servlet Life-Cycle Events

You can monitor and react to events in a servlet’s life cycle by defining listener objects whose methods get invoked when life cycle events occur. To use these listener objects, you must define the listener class and specify the listener class.

Defining The Listener Class

You define a listener class as an implementation of a listener interface. Table 10-3 lists the events that can be monitored and the corresponding interface that must be implemented. When a listener method is invoked, it is passed an event that contains information appropriate to the event. For example, the methods in the HttpSessionListener interface are passed anHttpSessionEvent, which contains an HttpSession.


Table 10-3 Servlet Life-Cycle Events 
Listener Interface and Event Class
Web context (See Accessing the Web Context) Initialization and destruction javax.servlet.ServletContextListener and
Attribute added, removed, or replaced javax.servlet.ServletContextAttributeListener and
Session (See Maintaining Client State) Creation, invalidation, and timeout javax.servlet.http.HttpSessionListener and
Attribute added, removed, or replaced javax.servlet.http.HttpSessionAttributeListener and


The listeners.ContextListener class creates and removes the database helper and counter objects used in the Duke’s Bookstore application. The methods retrieve the Web context object from ServletContextEvent and then store (and remove) the objects as servlet context attributes.

import database.BookDB;
import javax.servlet.*;
import util.Counter;

public final class ContextListener
   implements ServletContextListener {
   private ServletContext context = null;
   public void contextInitialized(ServletContextEvent event) {
      context = event.getServletContext();
      try {
         BookDB bookDB = new BookDB();
         context.setAttribute("bookDB", bookDB);
      } catch (Exception ex) {
            "Couldn't create database: " + ex.getMessage());
      Counter counter = new Counter();
      context.setAttribute("hitCounter", counter);
      context.log("Created hitCounter" + 
      counter = new Counter();
      context.setAttribute("orderCounter", counter);
      context.log("Created orderCounter" +

   public void contextDestroyed(ServletContextEvent event) {
      context = event.getServletContext();
      BookDB bookDB = context.getAttribute(

Specifying Event Listener Classes

You specify a listener class for a WAR in the deploytool Event Listeners inspector (see Event Listeners).

Handling Errors

Any number of exceptions can occur when a servlet is executed. The Web container will generate a default page containing the message A Servlet Exception Has Occurred when an exception occurs, but you can also specify that the container should return a specific error page for a given exception. You specify error pages for a WAR in the deploytool File Refs inspector (see Error Mapping).

Tagged , , , , , , ,