如何在tomcat启动的时候运行一个Java类

本文介绍如何通过实现ServletContextListener接口并在web.xml中配置Listener来运行特定的Java代码,该方法适用于Tomcat启动或应用部署时执行初始化任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

设置个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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值