如何在Tomcat启动或应用程序部署上运行特定的Java代码?

可能重复:
tomcat自动启动servlet
如何在tomcat服务器启动时加载java类(而不是servlet)

我在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中配置它

   mypackage.MyServletContextListener