Servlet Context Listener, Modifying the condition of a particular instance is known as an event. Servlet API(Application Program interface)2.4 onwards the event handling was introduced. Request , Session , and ServletContext objects are handled through Servlet Listeners. Event handling on request is used to keep track of the creation and destroy the request object and can be used to calculate the request processing time of each request. Following are the different methods and classes.
MyAppServletContextListener.java
[java]package servletlisteners;
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");
}
}[/java]
contextDestroyed Notification that the servlet context is about to be shut down. contextInitialized Notification that the web application initialization process is starting.
Web.xml
[xml]<web-app >
<listener>
<listener-class>
servletlisteners.MyAppServletContextListener
</listener-class>
</listener>
</web-app>[/xml]
Output
When compile the program output will be as follows in the console.
Summary
Key Points
Servlet Context Listener - While working with events tag should be added in web.xml
Servlet Context Listener - The initialized and destroy methods should be called.
Servlet Context Listener - Through WAR file source code file needs to be deploy in Tomcat.