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

后端 未结 3 2133
滥情空心
滥情空心 2021-02-14 20:10

Is there any method or API that I can use so that whenever I deploy a new WAR file, a part of code should execute or perhaps when Tomcat starts, the respective servlet should s

3条回答
  •  礼貌的吻别
    2021-02-14 20:39

    Reviving an old question since the only answer doesn't show any example.

    In order to run a custom piece of code whenever a web application WAR is deployed/undeployed or Tomcat is started/stopped, you need to:

    1. Implement the ServletContextListener listener and its methods contextInitialized() and contextDestroyed().
    2. Let Tomcat know about your implementation. According to the documentation, you can either add the implementing class to the deployment descriptor, annotate it with WebListener, or register it via 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 {
        /** The servlet context with which we are associated. */
        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 annotation or addListener() method):

    
        ...
        
            com.example.MyServletContextListener
        
    
    

提交回复
热议问题