Friday, September 11, 2009

Running Java Code when a Web App Starts or Stops

You can run Java code when a web application starts and stops by implementing ServletContextListener in your class. ServletContextListener requires two methods (an init and a destroy) and an entry in web.xml configuring the listener.

If you like, you can persist data beyond the initialization by creating static variables in your class.

See details here: http://www.java-tips.org/java-ee-tips/java-servlet/how-to-work-with-servletcontextlistener.html

Here's a quick version

package org.peter;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletContextEvent;

public class ServletListener implements ServletContextListener {

private ServletContext context = null;
static ArrayList lf = null;

/*This method is invoked when the Web Application has been removed
and is no longer able to accept requests
*/
public void contextDestroyed(ServletContextEvent event) {
//Output a simple message to the server's console
System.out.println("The web app has been removed");
this.context = null;
}

//This method is invoked when the Web Application
//is ready to service requests
public void contextInitialized(ServletContextEvent event) {
this.context = event.getServletContext();
System.out.println("Web app started up");
lf.add("foo");
} // end of Initialized
}


And the entry in web.xml:
<listener>
<listener-class>
org.peter.ServletListener
</listener-class>
</listener>

No comments:

Labels

Blog Archive

Contributors