Execute code on webapp startup and shutdown using ServletContextListener

Sometimes you are in need of invoking some code during startup and shutdown of your web application. There are several ways to achieve this, but in this post I'm going to take a look at the ServletContextListener.

How it works

ServletContextListener is an interface that gets notified about ServletContext lifecycle changes. It offers two methods.

  • contextInitialized - Is triggered when the web application is starting the initialization. This will be invoked before any of the filters and servlets are initialized.

  • contextDestroyed - Is triggered when the ServletContext is about to be destroyed. This will be invoked after all the servlets and filters have been destroyed.

Let's see how the ServletContextListener implementation could look.

package com.deadcoderising;

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

public class ExampleContextListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        System.out.println("Starting up!");
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        System.out.println("Shutting down!");
    }
}

How to add it to your web application

To add it to your web application, you should consider two options. You can specify the listener in the web.xml.

<listener>  
    <listener-class>
        com.deadcoderising.ExampleContextListener
    </listener-class>
</listener>  

Or you can use the @WebListener annotation. This annotation was introduced in Servlet 3.0 and will make sure that the web application will find your ServletContextListener implementation.

@WebListener
public class ExampleContextListener implements ServletContextListener {  
    // ...
}

Enjoyed the post?

If you don't want to miss future posts, make sure to subscribe