如何在上下文加载时自动运行java Web应用程序中的servlet /动作(tomcat启动)

cod*_*iot 1 java jsp servlets struts2

我想在我的web-app部署时执行一些代码.

如果我重新启动tomcat,也会发生同样的情况.

这应该只在整个Web应用程序的生命周期中完成一次.

有没有我可以在web.xml中设置的东西,比如启动条目,每次我部署我的web应用程序或重启tomcat时都会执行?

请帮忙.

Abu*_*kar 7

你需要实现ServletContextListner接口.

ServletContextListnerjavax.servlet包内.

这是一个关于如何做的简短代码.

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
    }

}
Run Code Online (Sandbox Code Playgroud)

并在部署描述符web.xml中配置它

<listener>
    <listener-class>
        mypackage.MyServletContextListener
    </listener-class>
</listener>
Run Code Online (Sandbox Code Playgroud)