Download
FAQ
History
PrevHomeNext API
Search
Feedback
Divider

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 request and response objects. Service methods are discussed in 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-0cycle events occur. To use these listener objects you must define and specify the listener class.

Defining the Listener Class

You define a listener class as an implementation of a listener interface. Table 11-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 an HttpSessionEvent, which contains an HttpSession.

Table 11-3 Servlet Life-Cycle Events 
Object
Event
Listener Interface and Event Class
Web context
(see Accessing the Web Context)
Initialization and destruction
Attribute added, removed, or replaced
Creation, invalidation, activation, passivation, and timeout
Attribute added, removed, or replaced
Request
A servlet request has started being processed by Web components
Attribute added, removed, or replaced

The listeners.ContextListener class creates and removes the database access 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.BookDBAO;
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 {
      BookDBAO bookDB = new BookDBAO();
      context.setAttribute("bookDB", bookDB);
    } catch (Exception ex) {
      System.out.println(
        "Couldn't create database: " + ex.getMessage());
    }
    Counter counter = new Counter();
    context.setAttribute("hitCounter", counter);
    counter = new Counter();
    context.setAttribute("orderCounter", counter);
  }

  public void contextDestroyed(ServletContextEvent event) {
    context = event.getServletContext();
    BookDBAO bookDB = context.getAttribute(
      "bookDB");
    bookDB.remove();
    context.removeAttribute("bookDB");
    context.removeAttribute("hitCounter");
    context.removeAttribute("orderCounter");
  }
} 

Specifying Event Listener Classes

You specify an event listener class in the Event Listener tab of the WAR inspector. Review step 11. in The Example Servlets for the deploytool procedure for specifying the ContextListener listener class.

Handling Errors

Any number of exceptions can occur when a servlet is executed. WHen an exception occurs, the Web container will generate a default page containing the message

A Servlet Exception Has Occurred 

But you can also specify that the container should return a specific error page for a given exception. Review step 12. in The Example Servlets for deploytool procedures for mapping the exceptions exception.BookNotFound, exception.BooksNotFound, and exception.OrderException returned by the Duke's Bookstore application to errorpage.html.

Divider
Download
FAQ
History
PrevHomeNext API
Search
Feedback
Divider

All of the material in The J2EE(TM) 1.4 Tutorial is copyright-protected and may not be published in other works without express written permission from Sun Microsystems.