[英]how to auto-run a servlet/action in a java web application whenever the context loads (tomcat starts)
I want to have some code executed whenever my web-app deploys. 每当我的Web应用程序部署时,我都希望执行一些代码。
The same should happen if I re-start tomcat. 如果我重新启动tomcat,也会发生同样的情况。
And this should be done only once in the life-cycle of the entire web-application. 并且在整个Web应用程序的生命周期中仅应执行一次。
Is there something which I can set in web.xml, something like a startup entry, which will be executed everytime I deploy my web-application or restart tomcat ? 是否可以在web.xml中设置某些内容,例如启动项,每次部署Web应用程序或重新启动tomcat时都会执行?
Please help. 请帮忙。
You need to implement ServletContextListner
interface. 您需要实现
ServletContextListner
接口。
ServletContextListner
is inside javax.servlet
package. ServletContextListner
在javax.servlet
包中。
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
}
}
And configure it in your deployment descriptor web.xml 并在您的部署描述符web.xml中进行配置
<listener>
<listener-class>
mypackage.MyServletContextListener
</listener-class>
</listener>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.