Servlets - SPLessons

Servlet Context Listener

Home > Lesson > Chapter 25
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Servlet Context Listener

Servlet Context Listener

shape Description

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.

Classes and Methods

shape Description

On request object On request attribute On ServletContext object On ServletContextAttribute On HttpSession object

shape Example

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

shape 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.