The revival of the old question, as the only answer does not show any example.
To run a custom piece of code whenever a WAR web application is deployed / not deployed or Tomcat starts / stops, you need to:
- Implement the
ServletContextListener listener and its contextInitialized() and contextDestroyed() methods. - Let Tomcat know about your implementation. According to the documentation, you can add an implementation class to the deployment descriptor, annotate it using
WebListener or register it using one of the addListener() methods defined on ServletContext .
Here is an example (based on this post ):
package com.example; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class MyServletContextListener implements ServletContextListener { private ServletContext context = null; @Override public void contextDestroyed(ServletContextEvent event) { log("Context destroyed"); this.context = null; } @Override public void contextInitialized(ServletContextEvent event) { this.context = event.getServletContext(); log("Context initialized"); } private void log(String message) { if (context != null) { context.log("MyServletContextListener: " + message); } else { System.out.println("MyServletContextListener: " + message); } } }
And add the following to web.xml (or, alternatively, use the WebListener or addListener() annotation method):
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> ... <listener> <listener-class>com.example.MyServletContextListener</listener-class> </listener> </web-app>
Mifeet
source share