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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13819773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 14:05:31  来源:igfitidea点击:

How to run specific java code on Tomcat start or on application deploy?

javatomcatservlets

提问by Timofei Davydik

Possible Duplicate:
tomcat auto start servlet
How do I load a java class (not a servlet) when the tomcat server starts

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

I have web application running on Tomcat server. I want to run specific code in my application once when Tomcat starts or when this application is deployed. How can I achieve it? Thanks

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

回答by Abubakkar

You need to implement ServletContextListner interface and write the code in it that you want to execute on tomcat start up.

您需要实现 ServletContextListner 接口并在其中编写要在 tomcat 启动时执行的代码。

Here is a brief description about it.

这是关于它的简要说明。

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 you need configure it in your deployment descriptor web.xml

你需要在你的部署描述符 web.xml 中配置它

<listener>
    <listener-class>
        mypackage.MyServletContextListener
    </listener-class>
</listener>