如何在tomcat啟動的時候運行一個Java類


設置個Listener就好了,在web.xml中指定描述。

web.xml其實就是tomcat啟動的時候會讀取的一個描述文件,比如訪問服務器的時候首頁等都可以在里面指定,有相應的tag。這里有解釋:http://blog.chinaunix.net/uid-20399471-id-1687965.html

實現這個Listener的接口:

 1 public class MyServletContextListener implements ServletContextListener {
 2 
 3   @Override
 4   public void contextDestroyed(ServletContextEvent arg0) {
 5     //Notification that the servlet context is about to be shut down.   
 6   }
 7 
 8   @Override
 9   public void contextInitialized(ServletContextEvent arg0) {
10     // do all the tasks that you need to perform just after the server starts
11 
12     //Notification that the web application initialization process is starting
13   }
14 
15 }

 

然后在web.xml中編寫listener的標簽,添加listener類:

MyTestListener換成自己實現ServletContextListener接口的類名
<listener>
     <listener-class>[package].MyTestListener</listener-class>
    </listener>
  

 

references:

http://stackoverflow.com/questions/13819773/how-to-run-specific-java-code-on-tomcat-start-or-on-application-deploy

http://stackoverflow.com/questions/158336/is-there-a-way-to-run-a-method-class-only-on-tomcat-startup

http://crunchify.com/how-to-run-java-program-automatically-on-tomcat-startup/

http://blog.sina.com.cn/s/blog_6ea90e4b0100ny3t.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM