如何在Tomcat start或应用程序部署上运行特定的java代码?
可能重复:如何在Tomcat start或应用程序部署上运行特定的java代码?,java,tomcat,servlets,Java,Tomcat,Servlets,可能重复: 我在Tomcat服务器上运行web应用程序。我希望在Tomcat启动或部署此应用程序时在应用程序中运行一次特定代码。我怎样才能做到呢?谢谢您需要实现ServletContextListner接口,并在其中编写要在tomcat启动时执行的代码 下面是对它的简要描述 ServletContextListner位于javax.servlet包中 下面是一个关于如何做的简短代码 public class MyServletContextListener implements Servle
我在Tomcat服务器上运行web应用程序。我希望在Tomcat启动或部署此应用程序时在应用程序中运行一次特定代码。我怎样才能做到呢?谢谢您需要实现ServletContextListner接口,并在其中编写要在tomcat启动时执行的代码 下面是对它的简要描述 ServletContextListner位于javax.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
}
}
您需要在部署描述符web.xml中配置它
<listener>
<listener-class>
mypackage.MyServletContextListener
</listener-class>
</listener>
mypackage.MyServletContextListener
您正在寻找一个名为“ServletContextListener”的东西,它有您需要的方法。请参阅查看@WebListener注释。我需要这个,它可以工作。还有“启动时加载”的方法。我的问题是这两个方法都初始化了类两次。有什么想法吗?我在这里看到了这个问题。我就是不知道该怎么办。不太熟悉Java,谢谢,非常有用