implementing javax.servlet.ServletContextListener

Each web application has a ServletContext associated with it. The ServletContext object is created when the application is started and is destroyed when the application is shut down. A ServletContext has a global scope and is similar to a global variable in an application. ServletContextListener will gets notified when servlet context gets initialization and destroyed.

A Simple example of implementing javax.servlet.ServletContextListener in your web application is shown below. You need to write one class implementing javax.servlet.ServletContextListener and it's methods. As shown below:
ContextListenerIMPL.java


package com.test;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class ContextListenerIMPL implements ServletContextListener {

 /** Creates a new instance of ContextListenerIMPL */
 public ContextListenerIMPL() { }

 public void contextInitialized(ServletContextEvent servletContextEvent) {

  //Code which should be executed just after web application context initialized should go here.
  //This code will be executed before any filter or servlet initialized.
  System.out.println("Web Application Context Initialized...");

 }
 public void contextDestroyed(ServletContextEvent servletContextEvent) {

  //Code which should be executed just before web application context gets destroyed should go here.
  //This code will be executed after all filter or servlet in the web application destroyed.
  System.out.println("Web Application Context destroyed...");

 }

}

Once writting ServletContextListener for your application you need to register it in WEB.XML file of your web application. As shown in bold letters below:
WEB.XML
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 . . . . . .
 <!-- Context Listener Config -->
 <listener>
  <listener-class>com.test.ContextListenerManager</listener-class>
 </listener>
 . . . . .
</web-app>

Other References:
ServletContextListener API Docs, Configuring Web Applications

Comments