ServletContextListener

It listens life cycle events of ServletContext object like creation and destruction .This interface defines the following two methods.

  1. public void contextInitialized(ServletContextEvent e)
  2. Executed automatically by the web Container at the time of context object creation.

  3. public void contextDestroyed(ServletContextEvent e)
  4. Executed automatically by the web Container at the time of context object destruction.

ServletContextEvent

ServletContextEvent is the child class of EventObject.This class contains only the following method

  1. public ServletContext getServletContext()

Example:

  1. Create a class ContextListenerDemo implementing ServletContextListener.
  2. Configure ContextListenerDemo in web.xml.
  3. Deploy & Run the application.

Create a class ContextListenerDemo implementing ServletContextListener

package com.java2learn.listener;

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

public class ContextListenerDemo implements ServletContextListener {

	public void contextInitialized(ServletContextEvent e) {

		System.out.println("ContextListenerDemo::contextInitialized");

	}

	public void contextDestroyed(ServletContextEvent e) {

		System.out.println("ContextListenerDemo::contextDestroyed");

	}

}

Configure ContextListenerDemo in web.xml.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>ListenersDemo</display-name>
	
	<listener>
		<listener-class>com.java2learn.listener.ContextListenerDemo</listener-class>
	</listener>
</web-app>

Deploy & Run the application.

Starting Server:
ServerStartup
Stopping Server:
stopServer

Final Project Structure:
PackageStructurecontextListener

Download Project: ListenerDemo

ServletContextAttributeListener

This Listener listens the events related to context scoped attributes.This interface defines the following 3 methods

  1. public void attributeAdded(ServletContextAttributeEvent e)
  2. public void attributeRemoved(ServletContextAttributeEvent e)
  3. public void attributeReplaced(ServletContextAttributeEvent e)
ServletContextAttributeEvent

This is the child class of ServletContextEvent.This class defines the following two methods

  1. public String getName()
  2. public String getValue()

ServletContextAttribute