They are discussed
in detail in Chapter 6 (The Application Events Framework). Here, though,
we 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 follows:
package.ListenerClass
Chapter 2 ?– Controlling Web Application Behavior with web.xml 94
For example, Listing 2.29 shows a simple listener called ContextReporter that
prints a message on the standard output whenever the Web application??™s Servlet-
Context is created (e.g., the Web application is loaded) or destroyed (e.g., the
server is shut down). Listing 2.30 shows the portion of the web.xml file that is
required for registration of the listener.
Listing 2.29 ContextReporter.java
package coreservlets;
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.
Pages:
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138