如何让 ServletContextListener 停止 Java EE 应用程序? [英] How can I make a ServletContextListener stop the Java EE application?

查看:28
本文介绍了如何让 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 抛出异常,Web 应用程序将无法正确加载并且应用程序服务器可能阻止所有后续请求(并以 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.

这篇关于如何让 ServletContextListener 停止 Java EE 应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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