Main Tutorials

ServletContextListener Example

The listener is something sitting there and wait for specified event happened, then “hijack” the event and run its own event.

Problem
You want to initialize a database connection pool before the web application is started, is there a “main ()” method in the web application environment?

Solution
The ServletContextListener is what you want, it will run your code before the web application is started.

1. ServletContextListener Example

In this example, we will show you how to create a custom listener class by implementing ServletContextListener, which run your code before the web application is started.

1.1 Create a class and implement the ServletContextListener interface.

MyAppServletContextListener.java

package com.mkyong.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class MyAppServletContextListener 
               implements ServletContextListener{
	
	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		System.out.println("ServletContextListener destroyed");
	}

        //Run this before web application is started
	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		System.out.println("ServletContextListener started");	
	}
}

1.2 Put it in the deployment descriptor.

web.xml

<web-app ...>
   <listener>
	<listener-class>
             com.mkyong.listener.MyAppServletContextListener 
        </listener-class>
   </listener>
</web-app>

1.3 Starting Tomcat….


//...
Dec 2, 2009 10:11:46 AM org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/6.0.20

ServletContextListener started   <-------------- Your code here, before we application --->

Dec 2, 2009 10:11:46 AM org.apache.coyote.http11.Http11Protocol start
INFO: Starting Coyote HTTP/1.1 on http-8080
//...
INFO: Server startup in 273 ms
Note
For Servlet container 3.x, you can annotate the listener with @WebListener, no need to declares in web.xml.

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
28 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
sachindra
7 years ago

Very precise and Perfect 🙂 ..Thank you Mkyong

Larry
9 years ago

Just wanted to say thanks for your informative articles. I find I am often looking for example code to show me how particular Java concepts and functions are used and Mkyong articles are always amongst the best of these. Precise and relevant.

Thanks again.

Marlon Falzetta
10 years ago

Very nice.

Its posible to add the annotation @WebListener in the class AppServletContextListener and remove the tag in web.xml.

mohsin azeem
10 years ago

Its posible to add the annotation @WebListener but when you are using serlvet 3.0

Avi
1 month ago

Thank you for this article but I am wondering if you have one filter defined through above way and other through web.xml how can you set up the priority specially when they both have same mapping pattern.

Amruta
1 year ago

helpful..

Bill
1 year ago

This is absolutely brilliant. Thanks very much.

Anurag
2 years ago

I am using a gradle application.
I have added @WebListner to listener class, its working fine when i am running as spring boot application. But Listner class is not envoked when try to run the same with tomcat

sanjar
4 years ago

Can we have session information when the context is destroyed?

Alessio
5 years ago

good

Aniruddh
7 years ago

Can we excecute Mysql queries in a class which inherits the “MyAppServletContextListener” class shown above??

Umair Aslam
8 years ago

great article. is there anything like ServletContextListener which could be used for after
web application is deployed, post application deployment hook

Someone
8 years ago

Just what I was looking for.

Thank you

Nikhil
9 years ago

A very precise tutorial !!!!

Dheeraj
9 years ago

Thanks a lot for the information and this solved my problem in just 5 mins

Hansi
10 years ago

can you please tell me how to start up the Tomcat in the third step. I used “/opt/apache-tomcat-7.0.34/bin$ ./startup.sh” commands. But it shows following lines.

Using CATALINA_BASE: /opt/apache-tomcat-7.0.34

Using CATALINA_HOME: /opt/apache-tomcat-7.0.34

Using CATALINA_TMPDIR: /opt/apache-tomcat-7.0.34/temp

Using JRE_HOME: /opt/java/jdk/jre

Using CLASSPATH: /opt/apache-tomcat-7.0.34/bin/bootstrap.jar:/opt/apache-tomcat-7.0.34/bin/tomcat-juli.jar

It did not invoke the methods in AppServletContextListener class.

Osama
10 years ago

This was reaaaly helpful
thank you sir

Manohar
10 years ago

Simple and clear example application to understand listeners. I understood my problem. I corrected it now. Thanks.

Pradhan Pitu
10 years ago

Nice article sir…it helped me a lot. Thanks for the post.

Satheesh Narayanan
10 years ago

Awesome. Thanks for the post/ its simple, neat and clean

Michael
10 years ago

Thanks!! A precise and to-the-point article. It helped.

Cristina
11 years ago

Thank you!!!

Is it possible to stop deployment if an error exists inside the contextInitialized class?
How to do it?
Thanks!

pavan
11 years ago

How to calculate the time between login and logout session.

padawan
10 years ago
Reply to  pavan

You should be kidding us

Manuel Gerstner
11 years ago

Thanks that was great help!

Sunil
11 years ago

Loved how well written this post is. You conveyed the use case and deployment very efficiently!
Its a pleasure to read this, thank you!

LALIT JAMNAL
4 years ago

Hi there, i am facing an issue with Threadlocal variables in the application. I want to close them manually at the end in the method contextDestroyed in the application context listener class. Could you please help?

Victor
10 years ago

We dont need Override annotation. We are not overriding anything, just implementing the listener methods