如何在Tomcat启动或应用程序部署上运行特定的Java代码? [英] How to run specific java code on Tomcat start or on application deploy?
问题描述
我在Tomcat服务器上运行Web应用程序。我想在Tomcat启动或部署此应用程序时在我的应用程序中运行特定代码。我怎样才能实现它?谢谢
I have web application running on Tomcat server. I want to run specific code in my application once when Tomcat starts or when this application is deployed. How can I achieve it? Thanks
推荐答案
您需要实现ServletContextListner接口并在其中编写要在tomcat启动时执行的代码。
You need to implement ServletContextListner interface and write the code in it that you want to execute on tomcat start up.
以下是关于它的简要说明。
Here is a brief description about it.
ServletContextListner位于javax.servlet包内。
ServletContextListner is inside javax.servlet package.
以下是有关如何操作的简短代码。
Here is a brief code on how to do it.
public class MyServletContextListener implements ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent arg0) {
//Notification that the servlet context is about to be shut down.
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
// do all the tasks that you need to perform just after the server starts
//Notification that the web application initialization process is starting
}
}
您需要在部署描述符web.xml中配置它
And you need configure it in your deployment descriptor web.xml
<listener>
<listener-class>
mypackage.MyServletContextListener
</listener-class>
</listener>
这篇关于如何在Tomcat启动或应用程序部署上运行特定的Java代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!