ServletContextListener a Servlet 3 Listener on Startup

You can listen to the startup of you web application with ServletContextListener. ServletContextListener allows you to initialise your application when it is deployed. Or clean up resources when the application is destroyed. In Servlet 3 you can register a listener with the @WebListener annotation. Here is an example how you can utilise the ServletContextListener to your advantage.

Project structure

|   +--main
|       +--java
|           +--com
|               +--memorynotfound
|                   |
|       |--resources
|       |--webapp

Maven Dependency


ServletContextListener a Servlet Listener on Startup

In order to listen to the event on startup you need to implement the javax.servlet.ServletContextListener class. This will require you to add two required methods. public void contextInitialized(ServletContextEvent event) and public void contextDestroyed(ServletContextEvent event) which allows you to manipulate the initialization and Destroy phases of your web application. Next we need to add the Servlet 3 @WebListener annotation to configure our application startup listener.

package com.memorynotfound;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

public class ApplicationStartUpListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent event) {
        System.out.println("---- initialize servlet context -----");
        // add initialization code here

    public void contextDestroyed(ServletContextEvent event) {
        System.out.println("---- destroying servlet context -----");
        // clean up resources

Note: If you prefer the web.xml servlet descriptor over the @WebListener annotation you can add the context listener as follows:

<web-app xmlns=""
                   " version="3.1">



When I deploy my application to a web container you’ll see that the contextInitialized() method is invoked. When I tear down the application you see that the contextDestroyed() method is invoked of the ServletContextListener.

[2015-01-13 06:14:26,870] Artifact servlet-context-listener:war exploded: Artifact is being deployed, please wait...
---- initialize servlet context -----
>> Tear down the application
---- destroying servlet context -----



You may also like...