Listener is something sitting there and wait for specified event happened, then “hijack” the event and run it’s own event.

Let’s say…

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

Solution

The “ServletContextListener” is what you want. It will make your code run before the web application is start.

ServletContextListener Example

1) Create a class and implement the ServletContextListener interface

package com.mkyong;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
 
public class AppServletContextListener implements ServletContextListener{
 
	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		System.out.println("ServletContextListener destroyed");
	}
 
	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		System.out.println("ServletContextListener started");	
	}
}

2) Put it in deployment descriptor

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

3)Start 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 is running --->
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

The ServletContextListener is running before the web application is start.

This article was posted in Servlet category.