Home  >  Q&A  >  body text

java - How to execute the project's initialization program when tomcat starts

When tomcat started, the console output a lot of information. The information showed that when tomcat started, many project configuration files were loaded, and the project initialization method was called, but I don't know how it was called. Where was it called? Do I need to configure something with tomcat?

PS:javaweb project

我想大声告诉你我想大声告诉你2685 days ago1046

reply all(4)I'll reply

  • PHP中文网

    PHP中文网2017-07-05 10:04:11

    Configure the following in web.xml

    <servlet>  
       <servlet-name>MyServlet</servlet-name>  
       <servlet-class>org.cai.MyServlet</servlet-class>  
       <strong><load-on-startup>0</load-on-startup></strong>  
      </servlet> 
    

    reply
    0
  • 某草草

    某草草2017-07-05 10:04:11

    Look for Listener in web.xml

    reply
    0
  • PHP中文网

    PHP中文网2017-07-05 10:04:11

    What the poster needs is for the system to understand the life cycle of Servlet. When you implement a Servlet, which of its methods will be called when the web application starts. There are too many articles about this:

    http://www.jianshu.com/p/1d50...
    http://www.runoob.com/servlet...

    reply
    0
  • 習慣沉默

    習慣沉默2017-07-05 10:04:11

    There are three ways:

    1. As @treeandgrass said, rewrite init() for a certain Servlet, but the premise is to set the value of load-on-startup in web.xml (or add the @WebServlet annotation);

    2. Implement init() for a certain Filter and add it to web.xml (or add @WebFilter annotation);

    3. Implement the ServletContextListener interface and implement contextInitialized(), and add it to web.xml (or add the @WebListener annotation).

    Among these three methods, I use the last one (ServletContextListener) most often (I usually only use this method when using Spring in the Web), because it always takes precedence over Filter and Servlet execution, and does not implement specific functions. Servlet and Filter are mixed together.

    Initialization work includes:

    • Initialization of thread pool, database connection pool, and network connection pool

    • Loading of IoC container

    • Start timer

    • Other objects that need to be initialized
      Most of the above initialization work needs to be closed when the web server stops. These tasks should be written in contextDestroyed().

    reply
    0
  • Cancelreply