如何使ServletContextListener停止Java EE应用程序?

问题描述:

我有一个ServletContextListener,它在我的Java EE应用程序启动时执行一些数据库管理功能。这在JPA和应用程序的其他部分启动/加载之前在我的应用程序中运行。如果数据库维护失败,我将记录错误。如果数据库维护失败,应用程序将无法正常运行,我想暂停应用程序。

I have a ServletContextListener which performs some database management functions when my Java EE application starts. This runs in my application before JPA and other pieces of the application are started/loaded. If the database maintenance fails I am logging the errors. If the database maintenance fails the application will not function properly and I would like to halt the application.

如何从ServletContextListener.contextInitialized中优雅正确地停止应用程序?

How can I gracefully and correctly stop the application from ServletContextListener.contextInitialized?

以下Viven给出的解决方案是关闭但不完全。当我抛出RuntimeException时,Glassfish处于不一致状态,其管理控制台无法访问,但某些进程仍在运行并保持端口3700(IIOP?)打开,从而阻止重启。

Solution given by Viven below is close but not quite. When I throw a RuntimeException Glassfish is left in an inconsistent state where its admin console is not accessible but some process is still running and keeping port 3700 (IIOP?) open which then prevents a restart.

如果你的 ServletContextListener 抛出异常,webapp将无法正确加载,应用服务器可能阻止所有后续请求(并以500错误响应)。

If your ServletContextListener throws an exception, the webapp won't load correctly and the application server may block all subsequent request (and respond with a 500 error).

这并不是完全阻止应用程序启动,也不是停止应用程序,而是防止进一步使用该应用程序并在您的情况下有用。

It isn't exactly preventing the application to start, nor stopping the application, but it prevents any further usage of the app and could be useful in your case.

在规范中进行适当验证后,此行为在规范中不是必需的。服务器可能(不是必须)返回500错误。因此,必须谨慎使用此解决方案。

After proper verification in the spec, this behaviour isn't mandatory in the specification. The server may (not must) return 500 errors. This solution has to be used carefully, therefore.

请参阅此答案来自Servlet规范的引用。

See this Answer for a quote from the Servlet spec.