如何在 Web 应用程序启动时(Tomcat 或其他)设置“配置检查”,如果不满足条件,则应用程序不应启动。
假设应用程序需要文件/tmp/dummy 存在于 fs 上才能启动。所以我有类似的东西
public class TestConfig {
public static void TestServerConfiguration() {
if (! new File("/tmp/dummy").exists()) {
// don't start this web application ...
}
}
}
我应该在哪里包含这个测试?
谢谢!
最佳答案
我会选择 ServletContextListner .与 servlet 答案一样,它不会停止 Tomcat,但会阻止加载 Web 应用程序。与 servlet 答案相比的一个优势来自 Javadoc:
All ServletContextListeners are notified of context initialization before any filters or servlets in the web application are initialized.
举个例子:
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class FileVerifierContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
// verify that the file exists. if not, throw a RuntimeException
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
}
}
以上假定您的 web.xml
指定了 Servlet 3.0 或更高版本的环境(或者您根本没有 web.xml
):
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
</web-app>
如果您使用的是较低的 servlet 规范,那么您需要删除 @WebListener
注释并在 web.xml
中声明监听器:
<web-app ...>
<listener>
<listener-class>
com.example.package.name.FileVerifierContextListener
</listener-class>
</listener>
</web-app>
关于tomcat - 如果配置不完整,则阻止(tomcat)Web 应用程序启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53306955/