Invokes the service method, passing request and response objects. Service methods are discussed in Writing Service Methods.

If it needs to remove the servlet, the container finalizes the servlet by
calling the servlet’s destroy method. For more information, see Finalizing a Servlet.

Handling Servlet Lifecycle Events

You can monitor and react to events in a servlet’s lifecycle by defining listener
objects whose methods get invoked when lifecycle 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 15-1
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 15-1 Servlet Lifecycle Events

Object

Event

Listener Interface and Event
Class

Web context

Initialization and destruction

javax.servlet.ServletContextListener and ServletContextEvent

Web context

Attribute added, removed, or replaced

javax.servlet.ServletContextAttributeListener and
ServletContextAttributeEvent

javax.servlet.http.HttpSessionAttributeListener and HttpSessionBindingEvent

Request

A servlet request has started being processed by web components

javax.servlet.ServletRequestListener
and ServletRequestEvent

Request

Attribute added, removed, or replaced

javax.servlet.ServletRequestAttributeListener and ServletRequestAttributeEvent

Use the @WebListener annotation to define a listener to get events for various
operations on the particular web application context. Classes annotated with @WebListener must implement one
of the following interfaces: