5.14. Designating Application Event Listeners

Application event listeners are classes that are notified when the servlet context or a session object is created or modified. They are new in version 2.3 of the servlet specification and are discussed in detail in Chapter 10 (The Application Events Framework). Here, though, I just want to briefly illustrate the use of the web.xml elements that are used to register a listener with the Web application.

Registering a listener involves simply placing a listener element inside the web-app element of web.xml. Inside the listener element, a listener-class element lists the fully qualified class name of the listener, as below.

<listener> 
  <listener-class>package.ListenerClass</listener-class> 
</listener> 

Although the structure of the listener element is simple, don’t forget that you have to properly order the subelements inside the web-app element. The listener element goes immediately before all the servlet elements and immediately after any filter-mapping elements. Furthermore, since application life-cycle listeners are new in version 2.3 of the servlet specification, you have to use the 2.3 version of the web.xml DTD, not the 2.2 version.

For example, Listing 5.20 shows a simple listener called ContextReporter that prints a message on the standard output whenever the Web application’s ServletContext is created (e.g., the Web application is loaded) or destroyed (e.g., the server is shut down). Listing 5.21 shows the portion of the web.xml file that is required for registration of the listener.

Listing 5.20. ContextReporter.java
package moreservlets; 

import javax.servlet.*; 
import java.util.*; 

/** Simple listener that prints a report on the standard output 
 *  when the ServletContext is created or destroyed. 
 */ 

public class ContextReporter implements ServletContextListener {
  public void contextInitialized(ServletContextEvent event) {
    System.out.println("Context created on " + 
                       new Date() + "."); 
  } 

  public void contextDestroyed(ServletContextEvent event) {
    System.out.println("Context destroyed on " + 
                       new Date() + "."); 
  } 
} 

Listing 5.21. web.xml (Excerpt declaring a listener)
<?xml version="1.0" encoding="ISO-8859-1"?> 
<!DOCTYPE web-app PUBLIC 
    "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" 
    "http://java.sun.com/dtd/web-app_2_3.dtd"> 

<web-app> 
  <!-- ... --> 
  <filter-mapping>...</filter-mapping> 
  <listener>
						<listener-class>moreservlets.ContextReporter</listener-class>
						</listener> 
  <servlet>...</servlet> 
  <!-- ... --> 
</web-app> 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.46.130