java - How to execute the project's initialization program when tomcat starts
我想大声告诉你
我想大声告诉你 2017-07-05 10:02:11
0
4
1083

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

我想大声告诉你
我想大声告诉你

reply all(4)
洪涛

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> 
某草草

Look for Listener in web.xml

洪涛

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...

習慣沉默

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().

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template