Skip to main content

Executing Tasks Portably at the Startup or Shutdown of a J2EE Application Server

Posted by inder on June 29, 2006 at 4:42 PM PDT

Enterprise applications often need to execute some tasks at the startup or shutdown of the Application Server. Many application servers provide proprietary ways of doing this, but there is a standard portable way as well. In this blog, I will discuss how this can be done using the Servlet API. This feature has been available since Servlet 2.3.

First, you need to write a class that implements the ServletContextListener interface:

public class MyStartupUtil implements ServletContextListener {

  public void contextInitialized (ServletContextEvent evt) {

    ServletContext sc = evt.getServletContext();

    // Place your code here that needs to be executed at application server startup

  }



  public void contextDestroyed (ServletContextEvent evt) {

    ServletContext sc = evt.getServletContext();

    // Place your code here that needs to be executed at application server shutdown

  }

}

This class needs to be configured in the web.xml deployment descriptor:

<listener>

    <listener-class>MyStartupUtil</listener-class>

</listener>

That's it. Now, whatever code you place in MyStartupUtil will get executed at the application server startup and shutdown.

Have you used this technique before? If so, what have been your experiences? Did it work well for you? Feel free to share your opinions or alternate techniques for doing the same through comments on this blog. Thanks for reading.

Related Topics >>