github.com/javahongxi

This article is reprinted from kaitao.hongxi.org

Application life cycle events

11.1 introduction

Application event facilities give Web application developers more control over the lifecycle of ServletContext, HttpSession, and ServletRequest, better code decomposition, and greater efficiency in managing resources used by Web applications.

 

11.2 Event Listeners

Application event listeners are classes that implement one or more Servlet event listener interfaces. They are instantiated and registered with the Web container when the Web application is deployed. They are provided by the developer in the WAR package.

Servlet event listeners support event notification when the ServletContext, HttpSession, and ServletRequest states change. Servlet context listeners are used to manage the state held at the resource or JVM level of the application. HTTP session listeners are used to manage the state or resources associated with a series of requests from the same client or user into a Web application. Servlet request listeners are used to manage the state of the entire Servlet request life cycle. Asynchronous listeners are used to manage asynchronous events, such as timeouts and completion of asynchronous processing.

Multiple listener classes can listen for each event type, and the developer can specify the order in which the container invokes the listener beans for each event type.

11.2.1 Event types and Listener Interfaces

The event type and listener interface are used to monitor the following table:

Table 11-1 Servlet context events

The event type describe Listener interface
The life cycle Either the Servlet context has just been created and is available to service its first request, or the Servlet context is about to close javax.servlet.ServletContextListener
Change the properties Attributes have been added, removed, or replaced in the Servlet context. javax.servlet.ServletContextAttributeListener

Table 11-2 HTTP session events

The event type describe Listener interface
The life cycle The session was created, destroyed, or timed out. javax.servlet.http.HttpSessionListener
Change the properties Attributes have been added, removed, or replaced on HttpSession. javax.servlet.http.HttpSessionAttributeListener
Session migration HttpSession has been activated or inactivated. javax.servlet.http.HttpSessionActivationListener
Object binding Object has been bound or unbound from HttpSession javax.servlet.http.HttpSessionBindingListener

 

Table 11-3 Servlet request events

The event type describe Listener interface
The life cycle A servlet request has been started to be processed by the Web component. javax.servlet.ServletRequestListener
Change the properties Properties have been added, removed, or replaced on the ServletRequest. javax.servlet.ServletRequestAttributeListener
Asynchronous events Timed out, connection terminated, or asynchronous processing completed javax.servlet.AsyncListener

 

An example of listener use

To illustrate the event usage scenario, consider a simple Web application that contains servlets that use a database. The developer provides a Servlet context listener class to manage database connections.

1. The listener class is notified when the application starts. The application logs into the database and stores connections in the servlet context.

2. Servlets in the application access connections as needed during the activity of the Web application.

3. When the Web server is shut down or the application is removed from the Web server, the listener class is notified and the database connection is closed.

11.3 Listener Class Configuration

11.3.1 Provides listener classes

Web application developers provide listener classes that implement one or more listener interfaces in the Javax. servlet API. Each listener class must have a no-parameter constructor. Listener classes are packaged into a WAR package, either under the WEB-INF/classes archive or inside a JAR in the Web-INF /lib directory.

11.3.2 Deployment Statement

The listener class uses the Listener element declaration in the Web application deployment descriptor. The order in which they are listed by class name is the order in which they are called. Unlike other listeners, AsyncListener type listeners may only be programmatically registered (using a ServletRequest).

11.3.3 Listener Registration

The Web container creates an instance of each listener class and registers it for event notifications before the application processes the first request. Web containers register listener instances based on the interface they implement and in the order in which they appear in the deployment descriptor. During the execution of the Web application, listeners are invoked in the order in which they were registered.

11.3.4 Notification upon shutdown

When the application is closed, listeners are notified in the reverse order in which they are declared, and the notification session listener precedes the notification context listener. Notifying the session listener that the session is invalid must be done before the notifying context listener is closed.

11.4 Example deployment descriptors

The following example is the deployment syntax for registering two Servlet context lifecycle listeners and one HttpSession listener.

Hypothesis com. Acme. MyConnectionManager and com. Acme. MyLoggingModule both realized the javax.mail. Servlet. ServletContextListener, And com. Acme. MyLoggingModule and implements the javax.mail. Servlet. HTTP. HttpSessionListener. In addition, the developers hope com. Acme. MyConnectionManager in com. Acme. MyLoggingModule receive a phone call from the Servlet context lifecycle events. Here is the deployment descriptor for this application:

<web-app>  
    <display-name>MyListeningApplication</display-name>  
    <listener>  
        <listener-class>com.acme.MyConnectionManager</listener-class>  
    </listener>  
    <listener>  
        <listener-class>com.acme.MyLoggingModule</listener-class>  
    </listener>  
    <servlet>  
        <display-name>RegistrationServlet</display-name>...etc  
    </servlet>  
</web-app>
Copy the code

  

 

11.5 Listener instances and threads

The container needs to complete the instantiation of the listener class in the Web application before it starts executing the first request into the application. The container must keep a reference to each listener until the last request of the Web application is serviced.

Attribute changes to the ServletContext and HttpSession objects may occur simultaneously. The container is not required to synchronize notifications generated by the property listener class. A state-maintaining listener class is responsible for data integrity and should explicitly handle this situation.

11.6 Listener Is Abnormal

Application code inside a listener may throw an exception at runtime. Some listener notifications occur during another component call tree in the application. An example of this is a Servlet that sets session properties and the session listener throws an unhandled exception. The container must allow unhandled exceptions to be handled by the error page mechanism described in Section 10.9, “Error Handling.” If no error page is specified for these exceptions, the container must ensure that a response with a status code of 500 is returned. In this case, no more listeners are invoked based on events.

Some exceptions do not occur during another component call stack in the application. An example of this is SessionListener, where the session receiving the notification has timed out and throws an unhandled exception, or ServletContextListener throws an unhandled exception during Servlet context initialization of the notification, Or the ServletRequestListener throws an unhandled exception during notification of initialization or destruction of the request object. In this case, the developer has no opportunity to handle the exception. The container can respond to all subsequent requests to the Web application with an HTTP status code of 500, indicating that the application has failed.

Developers expect normal handling to occur after listeners raise an exception and must handle their own exceptions in the notification methods.

11.7 Distributed Container

In a distributed Web container, the HttpSession instance is restricted to a specific JVM service session request, and the ServletContext object is restricted to the JVM in which the Web container resides. Distributed containers do not need to propagate Servlet context events or HttpSession events to other JVMS. Listener class instances are restricted to one declaration per deployment descriptor per JVM.

11.8 Session Events

Listener classes provide developers with a way to track conversations within a Web application. It is often useful in tracing sessions to know whether a session has become invalid because the container timed out the session, or because an in-app Web component called the invalidate method. This distinction may indirectly determine the use of listeners and HttpSession API methods.