| Refresh | Home EGTry.com

web application initialization using ServletContextListener


1. configure an event ServletContextListener class in web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app 
  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" 
  version="2.5">
  <display-name>a simple web application</display-name> 

  <listener>
    <listener-class>com.egtry.TestListener</listener-class>
  </listener>
  
</web-app>


2. implementation of the ServletContextListener

package com.egtry;

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

public class TestListener implements ServletContextListener {
	@Override
	public void contextInitialized(ServletContextEvent cEvent) {
		ServletContext context=cEvent.getServletContext();
		System.out.println("servlet context is been initializing for the context: "+context.getContextPath());
	}
	
	@Override
	public void contextDestroyed(ServletContextEvent cEvent) {
		ServletContext context=cEvent.getServletContext();
		System.out.println("servlet context is about to be destroyed");	
	}
}