Example of ServletContextListener Implementation

According to Oracle official documenentation, the ServletContextListener Interface is responsible for receiving notifications about the ServletContext lifecycle changes, more specifically its initialization and destruction. This can be really helpful for developers in some specific situations, like for example when we need to execute a block of code right before the application starts or shut down.

In this short tutorial I’m going give a really simple example of a ServletContextListener Implementation.

With our Java Web project created let’s create a Java class that implements the ServletContextListener interface, it should look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package tech.fourDev.servletContextListenerSample;
 
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
 
public class ServletContextListenerSample implements ServletContextListener{
 
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("INITIALIZED");
    }
 
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("DESTROYED");
    }   
}

This is our listener, you can see that I’ve already implemented the contextInitialized and contextDestroyed methods, as the name suggests the first one will be called when the ServletContext starts and the other one when it gets destroyed.

There is just one more thing to be done before you can run your application, you need to register this listener in your web.xml:

1
2
3
<listener>
    <listener-class>tech.fourDev.servletContextListenerSample.ServletContextListenerSample</listener-class>
</listener>

Perfect! Now if you run your application you’ll see the word “INITIALIZED” printed when you deploy your project and the word “DESTROYED” when you undeploy or redeploy it.

Recommended for you

Leave a Reply

Your email address will not be published. Required fields are marked *

Obs: Use the tag <pre lang="LANGUAGE"> to include code blocks to your comment.
Example: <pre lang="javascript"> console.log('Test'); </pre>