Execute servlet on startup of the application

后端 未结 3 1673
野的像风
野的像风 2021-01-15 11:28

I build a web application with JSPs and in my servlet I have:

public class MyServlet extends HttpServlet {
    protected void processRequest(HttpServletReque         


        
相关标签:
3条回答
  • 2021-01-15 12:12

    In my point of view, a good way is to implement a Servlet Context Listener. It listens to application startup and shutdown.

    public class YourListener implements javax.servlet.ServletContextListener {
    
        public void contextInitialized(ServletContextEvent sce) {
        }
    
        public void contextDestroyed(ServletContextEvent sce) {
        }
    }
    

    And then, you configure the listener in your web.xml () or with the @WebServletContextListener annotation.

    0 讨论(0)
  • 2021-01-15 12:21

    You can configure it in Tomcat's web.xml (or corresponding configuration files in similar servers), like below using the tag <load-on-startup> :

    <servlet>
        <servlet-name>MyOwnServlet</servlet-name>
        <servlet-class>MyServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
     </servlet>
    
    0 讨论(0)
  • 2021-01-15 12:23

    Whatever you want done on startup should be done by a class implementing ServletContextListener, so you should write such a class, for example:

    public class MyContextListener 
               implements ServletContextListener{
    
      @Override
      public void contextDestroyed(ServletContextEvent arg0) {
        //do stuff
      }
    
      @Override
      public void contextInitialized(ServletContextEvent arg0) {
        //do stuff before web application is started
      }
    }
    

    Then you should declare it in web.xml:

    <listener>
       <listener-class>
          com.whatever.MyContextListener 
       </listener-class>
    </listener>
    
    0 讨论(0)
提交回复
热议问题