Implementations of this interface recieve notifications about changes to the servlet context of the web application they are part of. To recieve notification events, the implementation class must be configured in the deployment descriptor for the web application.
public interface ServletContextListener extends EventListener
Interface for receiving notification events about ServletContext lifecycle changes.
Methods Summary
void contextDestroyed(ServletContextEvent sce)
Notification that the servlet context is about to be shut down.
All servlets and filters will have been destroyed before any ServletContextListeners are notified of context destruction.
void contextInitialized(ServletContextEvent sce)
Notification that the web application is ready to process requests.
All ServletContextListeners are notified of context initialization before any filters or servlets in the web application are initialized.
Set the deployment descriptor.
web.xml (Servlet < 3.0)
Sample web.xml file:
<?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">
...
<listener>
<listener-class>example.ExampleApplicationLifeCycleListener</listener-class>
</listener>
...
</web-app>
@WebListener (Servlet >= 3.0)
The WebListener annotation is used to register the following types of listeners
- Context Listener (javax.servlet.ServletContextListener)
- Context Attribute Listener (javax.servlet.ServletContextAttributeListener)
- Servlet Request Listener (javax.servlet.ServletRequestListener)
- Servlet Request Attribute Listener (javax.servlet.ServletRequestAttributeListener)
- Http Session Listener (javax.servlet.http.HttpSessionListener)
- Http Session Attribute Listener (javax.servlet.http.HttpSessionAttributeListener)
Example
Registering ServletContextListeners, which run your code before the web application is started. It waits for specified event happened, then “hijack” the event and run its own event.
Problem You want to initialize a database connection pool before the web application is started, is there a “main()” method in the web application environment?
Solution The ServletContextListener is what you want, it will run your code before the web application is started.
1 | package example; |
References
- https://www.ntu.edu.sg/home/ehchua/programming/java/JavaServlets.html
- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api/3.1.0
- http://blog.caucho.com/2009/10/06/servlet-30-tutorial-weblistener-webservlet-webfilter-and-webinitparam/
- https://www.mkyong.com/servlet/what-is-listener-servletcontextlistener-example/