tomcat - Can some code run when we first deploy a WAR file? -


Is there a way or API that I can use so that whenever I run a new war file, the code A part should be executed, or maybe when the Tomcat starts, the respective servicelet should start some code continuously or run.

Reviving an old question as the sole answer does not show any examples.

Whenever a web application war is deployed / unchanged or a tomcat is started / stopped, you need it:

  1. AllContact Listener Implement the listener and its method contextInitialized () and contextDestroyed () .
  2. Know Tomcat about your implementation Accordingly, you can either add the implementation class to the deployment descriptor, annotate it with the WebListener or < Code> addListener () methods can define ServletContext .

    Here is an example (on the basis of):

      package com.example; Import javax.servlet.ServletContext; Import javax.servlet.ServletContextEvent; Import javax.servlet.ServletContextListener; Public category MyServletContextListener applies ServletContextListener {/ ** servlet reference with which we are connected * / private servlet contact reference = null; @ Override Public Records Produced Stretched (SerialContactEvent Event) {Log ("Discovered Destroyed"); This.context = null; } @ Override Public Zero Reference Start (ServletContextEvent Event) {this.context = event.getServletContext (); Logs ("get started"); } Private zero log (string message) {if (context! = Null) {context.log ("MyServletContextListener:" + message); } Else {System.out.println ("MyServletContextListener:" + Message); }}   

    and web.xml add the following (or alternatively, use the WebListener annotation or addListener () Method):

      & lt; 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 "axis: schema location =" http://java.sun.com/xml/ns/j2ee http: //java.sun .com / xml / ns / j2ee / web app_2_4.xsd "& gt; ... & lt; Listener & gt; & Lt; Audience category & gt; Com.example.MyServletContextListener & lt; / Listener Category & gt; & Lt; / Listener & gt; & Lt; / Web application & gt;    

Comments