How to Run a Code Immediately After the Web Application or Context is Deployed in Tomcat

If are writing a web app using Java (JSP or Servlets), sometime we want to execute a code section immediately after the application context has deployed. For examples to:
  • Initialize Caching system
  • Initialize some scheduling services
  • Put some data is application scope that will be needed frequently.
Before Servlets 2.4, such code was put in a normal Serlvet, which was configured in web.xml to run at startup. But in Servlets 2.4, there is explicit mechanism to do so. Here is how you can do it:

  1. Make a class MyListener that implements ServletContextListener
  2. Write the code you want to run only once (after the context is loaded, i.e. when the web application is deployed in Tomcat) in contextInitialized(ServletContextEvent cse) method.
package mypackage;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class MyListener implements ServletContextListener {

public void contextInitialized(ServletContextEvent cse) {
//write you code here ...

public void contextDestroyed(ServletContextEvent cse) {
// write java code here that you want to run after the context is destroyed.

After you have done it. Configure you Listener in web.xml like this:

Please note that, the code written in Listener classes run even before the run-on-startup Servlets. And if need to write multiple Listener. Make sure you put then in right order. The Listeners are executed in the order they are configured.