Handling Servlet Life-Cycle Events
Handling Servlet Life-Cycle Events
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
and specify the listener class.
Defining the Listener Class
You define a listener class as an implementation of a listener interface.
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 42
Servlet Life-Cycle Events
Object
Event
Listener Interface and Event Class
Web context (see
Initialization and
destruction
and
Attribute added,
removed, or replaced
and
Session (See
Creation,
invalidation,
activation,
passivation, and
timeout
Attribute added,
removed, or replaced
and
Request
A servlet request has
started being
processed by web
components
and
Attribute added,
removed, or replaced
and
The
tut-install/javaeetutorial5/examples/web/bookstore1/src/java/com/sun/bookstore1/listeners/ContextListen
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.
Servlet Life Cycle
Chapter 4 · Java Servlet Technology
103