10.12.2012 Views

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Handling Servlet Life-Cycle Events<br />

You can monitor and react to events in a servlet’s life cycle by defining listener objects whose<br />

methods get invoked when life-cycle events occur. To use these listener objects you must define<br />

and specify the listener class.<br />

Defining the Listener Class<br />

You define a listener class as an implementation of a listener interface. Table 4–2 lists the events<br />

that can be monitored and the corresponding interface that must be implemented. When a<br />

listener method is invoked, it is passed an event that contains information appropriate to the<br />

event. For example, the methods in the HttpSessionListener interface are passed an<br />

HttpSessionEvent, which contains an HttpSession.<br />

TABLE 4–2 Servlet Life-Cycle Events<br />

Object Event Listener Interface and Event Class<br />

Web context (see<br />

“Accessing the Web<br />

Context” on page 124)<br />

Session (See<br />

“Maintaining Client<br />

State” on page 125)<br />

Initialization and<br />

destruction<br />

Attribute added,<br />

removed, or replaced<br />

Creation,<br />

invalidation,<br />

activation,<br />

passivation, and<br />

timeout<br />

Attribute added,<br />

removed, or replaced<br />

Request A servlet request has<br />

started being<br />

processed by web<br />

components<br />

Attribute added,<br />

removed, or replaced<br />

javax.servlet.ServletContextListener and<br />

ServletContextEvent<br />

javax.servlet.ServletContextAttributeListener and<br />

ServletContextAttributeEvent<br />

javax.servlet.http.HttpSessionListener,<br />

javax.servlet.http.HttpSessionActivationListener,<br />

and<br />

HttpSessionEvent<br />

javax.servlet.http.HttpSessionAttributeListener and<br />

HttpSessionBindingEvent<br />

javax.servlet.ServletRequestListener and<br />

ServletRequestEvent<br />

javax.servlet.ServletRequestAttributeListener and<br />

ServletRequestAttributeEvent<br />

Servlet Life Cycle<br />

<strong>The</strong><br />

tut-install/javaeetutorial5/examples/web/bookstore1/src/java/com/sun/bookstore1/listener<br />

class creates and removes the database access and counter objects used in the Duke’s Bookstore<br />

application. <strong>The</strong> methods retrieve the web context object from ServletContextEvent and then<br />

store (and remove) the objects as servlet context attributes.<br />

Chapter 4 • <strong>Java</strong> ServletTechnology 103

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!