Skip to Main Content
Jakarta Struts Cookbook
book

Jakarta Struts Cookbook

by Bill Siggelkow
February 2005
Intermediate to advanced content levelIntermediate to advanced
528 pages
12h 53m
English
O'Reilly Media, Inc.
Content preview from Jakarta Struts Cookbook

7.1. Performing Tasks at Application Startup

Problem

You want to be notified when your web application is initialized so you can preload application-scope data or execute other startup functions.

Solution

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.xml

Discussion

Every Java web application has one single ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming Jakarta Struts

Programming Jakarta Struts

Chuck Cavaness
Beginning Spring Framework 2

Beginning Spring Framework 2

Bruce Snyder, Sing Li, Anne Horton, Thomas Van de Velde, Naveen Balani, Christian Dupuis
Java Cookbook

Java Cookbook

Ian F. Darwin
Struts 2 in Action

Struts 2 in Action

J. Scott Stanlick, Chad Michael Davis, Donald J. Brown

Publisher Resources

ISBN: 059600771XSupplemental ContentErrata Page