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
+--src
| +--main
| +--java
| +--com
| +--memorynotfound
| |--ApplicationStartUpListener.java
| |--resources
| |--webapp
pom.xml
Maven Dependency
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
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;
@WebListener
public class ApplicationStartUpListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
System.out.println("---- initialize servlet context -----");
// add initialization code here
}
@Override
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="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<listener>
<listener-class>com.memorynotfound.ApplicationStartUpListener</listener-class>
</listener>
</web-app>
Demo
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 -----