如何在Tomcat启动或应用程序部署上运行特定的Java代码? [英] How to run specific java code on Tomcat start or on application deploy?

查看:604
本文介绍了如何在Tomcat启动或应用程序部署上运行特定的Java代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

tomcat自动启动servlet

如何在tomcat服务器启动时加载java类(而不是servlet)

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

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

推荐答案

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

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

以下是关于它的简要说明。

Here is a brief description about it.

ServletContextListner位于javax.servlet包内。

ServletContextListner is inside javax.servlet package.

以下是有关如何操作的简短代码。

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
  }

}

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

And you need configure it in your deployment descriptor web.xml

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

这篇关于如何在Tomcat启动或应用程序部署上运行特定的Java代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆