February 2005
Intermediate to advanced
528 pages
12h 53m
English
You want to be notified when your web application is initialized so you can preload application-scope data or execute other startup functions.
Create a class that implements the
ServletContextListener
interface. The class shown in Example 7-1 stores the
current date and time in the servlet context when the application is
started.
Example 7-1. Servlet context data loader
package com.oreilly.strutsckbk.ch07;
import java.util.Date;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class ContextLoader implements ServletContextListener {
public void contextInitialized(ServletContextEvent event) {
ServletContext ctx = event.getServletContext( );
ctx.setAttribute("dateStarted", new Date( ));
}
public void contextDestroyed(ServletContextEvent event) {
// clean up here
}
}Declare the class with a listener element in your
web application's
web.xml
file. The listener element is supported by Version
2.3 or 2.4 of the Servlet specification; the DTD must specify Version
2.3 or 2.4:
<?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>
<display-name>Struts Cookbook - Chapter 7 Examples</display-name>
<listener>
<listener-class>com.oreilly.strutsckbk.ch07.ContextLoader
</listener-class>
</listener>
... rest of web.xmlEvery Java web application has one single ...