【问题标题】:How to run specific java code on Tomcat start or on application deploy? [duplicate]如何在 Tomcat 启动或应用程序部署上运行特定的 java 代码? [复制]
【发布时间】:2012-12-11 11:49:56
【问题描述】:

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

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

【问题讨论】:

标签: java tomcat servlets


【解决方案1】:

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

【讨论】:

  • 还要查看@WebListener 注释。
  • 我需要这个并且它有效。还有一种“启动时加载”的方法。我的问题是这两种方法都将类初始化了两次。任何的想法?我在这里看到了这个问题stackoverflow.com/questions/7301088/…。我只是不明白该怎么做。对Java不太熟悉。
  • 谢谢,很有用
  • 如果我的 &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener 怎么办?我的 tomcat 服务器会首先调用哪种方法?我的意思是,哪个是我的应用程序的入口点?
猜你喜欢
  • 2011-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-14
  • 2011-03-16
  • 2016-12-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多