简体   繁体   English

java web-application初始化和关闭

[英]java web-application initialization and shutdown

I'm trying to implements initialization and shutdown of a webapp. 我正在尝试实现webapp的初始化和关闭。 That includes initialization and shutdown of: 这包括初始化和关闭:

  • Hibernate (v3.6); Hibernate(v3.6);
  • C3P0 (v0.9.1.2); C3P0(v0.9.1.2);
  • EHCache (v2.3.0); EHCache(v2.3.0);
  • Quartz (1.8.4); 石英(1.8.4);
  • Other tasks specific to my webapp; 我的webapp特有的其他任务;

Using Tomcat 5.5.30 and Java 6. My idea is to avoid resource leaking, mostly because of the redeploy of the webapp in the development environment. 使用Tomcat 5.5.30和Java 6.我的想法是避免资源泄漏,主要是因为在开发环境中重新部署了webapp。

How should I implement this? 我该如何实现呢?

Usually for Web initialization and shutdown, you will write a ServletContextListener . 通常对于Web初始化和关闭,您将编写ServletContextListener

The steps to do this are: 执行此操作的步骤是:

  1. Write a class that implements javax.Servlet.ServletContextListener 编写一个实现javax.Servlet.ServletContextListener的类
  2. Add a tag to web.xml deployment descriptor to register the class you've just created 将标记添加到web.xml部署描述符以注册刚刚创建的类
  3. Deploy your application 部署您的应用程序

When you deploy your application, contextInitialized method will be called. 部署应用程序时,将调用contextInitialized方法。 You can place all initialization you want here. 您可以在此处放置所需的所有初始化。 On application shutdown contextDestroyed method will be called. 在应用程序关闭时,将调用contextDestroyed方法。

Its also possible to use the HTTP Servlet instead but the listener is a better option. 它也可以使用HTTP Servlet,但是监听器是更好的选择。

You have to extend a class with HttpServlet and setting the following stuff to your web.xml: 您必须使用HttpServlet扩展一个类并将以下内容设置到您的web.xml:

<servlet>
    <servlet-name>StartupServlet</servlet-name>
    <servlet-class>your.package.servlets.StartupServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

The class can overwrite the init and the destroy method. 该类可以覆盖init和destroy方法。

但是,如果应用程序崩溃并且未调用正常关闭例程,您仍然希望以这样的方式管理资源:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM