Java Servlet Context Listener Example
In this tutorial, I will be demonstrating a simple example of how to use ServletContextListener to make some global initializations and configurations. We will be using WildFly application server and Eclipse to demonstrate the examples in this post. None database is required to run this example.
1. Introduction
ServletContext is a configuration object which is created when application server starts and gets destroyed when the application server stops. ServletConfig is created for every servlet, ServletContext is one for every web application. ServletContextListener is an interface for receiving notification events about ServletContext lifestyle changes. This is typically used for database initializations, cleanup etc.,
2. Creation of Listener
A servlet context listener can be created using several approaches. We first have to implement ServletContextListener interface. Once created, we have to register this class as a listener. There are three ways to do that. First approach and the simplest is to use WebListener annotation. Another approach is to declare this class in web.xml or we can also use ServletContext’s addListener method. In this example, we will be taking the first approach.
Let us first create a new Dynamic Web Project. Right click in Project Explorer of eclipse and choose New -> Dynamic Web Project. This will bring up a new project wizard. Give the project name and choose the target run time to be your application server’s runtime.
You can click finish, as we don’t have to worry about any more setting to observe servlet context listeners. Open src folder and right click to create a new class name it TestListener and place it in any package of your choosing. In this example, I am placing it in org.jcg package. Annotate the class with WebListener annotation and implement ServletContextListener interface. Implementing ServletContextListener forces us to implement two methods contextInitialized(ServletContextEvent) and
contextDestroyed(ServletContextEvent) which are called upon starting and stopping of application server respectively. Following is the code
TestListener.java
package org.jcg; import javax.servlet.*; import javax.servlet.annotation.WebListener; @WebListener public class TestListener implements ServletContextListener { @Override public void contextDestroyed(ServletContextEvent arg0) { System.out.println("Server stopped"); } @Override public void contextInitialized(ServletContextEvent arg0) { System.out.println("Server started"); } }
Create this class in any package of your choice in a new Dynamic Web Project. Above class simply prints Server started and Server stopped when application server starts and stops respectively.You can create as many listeners as you wanted however each of them will be executed only once during startup and once during shutdown.
3. Life Cycle
Once application server receives a startup request, it will look for any classes registered as servlet context listeners. Once identified, contextInitialized method of every class is executed and app-server will complete it’s startup process.
Once started, application server will not be interacting with these listeners anymore. However when shutdown signal is received, app-server will call context destroyed methods of all the listeners before shutdown is completed.
4. Deploy and Run
Right click on the project and choose Run As -> Run on Server. As shown in the below screenshot.
Choose Your application server in the , in this example I’m using WildFly Application Server. I should see log like this.
23:17:50,613 INFO [org.jboss.ws.common.management] (MSC service thread 1-4) JBWS022052: Starting JBossWS 5.1.5.Final (Apache CXF 3.1.6) [stdout] (ServerService Thread Pool -- 63) Server started [org.wildfly.extension.undertow] (ServerService Thread Pool -- 63) WFLYUT0021: Registered web context: /servlet-context-listener-example [org.jboss.as.server] (ServerService Thread Pool -- 34) WFLYSRV0010: Deployed "servlet-context-listener-example.war" (runtime-name : "servlet-context-listener-example.war") [org.jboss.as] (Controller Boot Thread) WFLYSRV0025: WildFly Full 10.1.0.Final (WildFly Core 2.2.0.Final) started in 4106ms - Started 405 of 655 services (404 services are lazy, passive or on-demand)
Observe line 2 to see the message we printed before application server startup is complete. Now, inorder to observe the server stopped message from contextDestroyed method, we need to stop the application server. To stop the application server cleanly, go to the bin folder of WildFly installation folder, and run the following command.
jboss-cli.sh -c --command=:shutdown
This will shutdown the application server cleanly and you should see the message like this
23:18:08,195 INFO [org.jboss.as.server] (Management Triggered Shutdown) WFLYSRV0241: Shutting down in response to management operation 'shutdown' [org.wildfly.extension.undertow] (ServerService Thread Pool -- 11) WFLYUT0022: Unregistered web context: /servlet-context-listener-example [stdout] (ServerService Thread Pool -- 11) Server stopped [org.wildfly.extension.undertow] (MSC service thread 1-7) WFLYUT0019: Host default-host stopping … [org.jboss.as.server.deployment] (MSC service thread 1-3) WFLYSRV0028: Stopped deployment servlet-context-listener-example.war (runtime-name: servlet-context-listener-example.war) in 34ms … [org.jboss.as] (MSC service thread 1-8) WFLYSRV0050: WildFly Full 10.1.0.Final (WildFly Core 2.2.0.Final) stopped in 45ms
Keep in mind that you won’t see the Server stopped message if you forcibly end the server process in eclipse by clicking stop button. It will only be executed when the application server stops cleanly. Which is why we executed the jboss-cli shell script.
5. Summary
- ServletContextListener is an interface, which can be used to create concrete context listeners
- Implementing this interface and marking the class with @WebListener annotation will register the class as a context listener
- Every Context Listener’s contextInitiailzed method will be called before server startup is complete
- On clean server shutdown, contextDestroyed of every context listener will be executed