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 the Author

author image
mkyong
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

avatar
22 Comment threads
2 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
24 Comment authors
LALIT JAMNALsanjarAlessiosachindraAniruddh Recent comment authors
newest oldest most voted
sachindra
Guest
sachindra

Very precise and Perfect :) ..Thank you Mkyong

Marlon Falzetta
Guest
Marlon Falzetta

Very nice.

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

mohsin azeem
Guest
mohsin azeem

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

LALIT JAMNAL
Guest
LALIT JAMNAL

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?

sanjar
Guest
sanjar

Can we have session information when the context is destroyed?

Alessio
Guest
Alessio

good

Aniruddh
Guest
Aniruddh

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

Umair Aslam
Guest
Umair Aslam

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

Someone
Guest
Someone

Just what I was looking for.

Thank you

Nikhil
Guest
Nikhil

A very precise tutorial !!!!

Larry
Guest
Larry

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.

Dheeraj
Guest
Dheeraj

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

Hansi
Guest
Hansi

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
Guest
Osama

This was reaaaly helpful
thank you sir

Manohar
Guest
Manohar

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

Pradhan Pitu
Guest
Pradhan Pitu

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

Satheesh Narayanan
Guest
Satheesh Narayanan

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

Michael
Guest
Michael

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

Cristina
Guest
Cristina

Thank you!!!

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

pavan
Guest
pavan

How to calculate the time between login and logout session.

padawan
Guest
padawan

You should be kidding us

Manuel Gerstner
Guest
Manuel Gerstner

Thanks that was great help!

Sunil
Guest
Sunil

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

Victor
Guest
Victor

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