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

时间:2012-12-11 11:49:56

标签: java tomcat servlets

  

可能重复:
  tomcat auto start servlet
  How do I load a java class (not a servlet) when the tomcat server starts

我在Tomcat服务器上运行Web应用程序。我想在Tomcat启动或部署此应用程序时在我的应用程序中运行特定代码。我怎样才能实现它?感谢

1 个答案:

答案 0 :(得分:29)

您需要实现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>