如果配置不完整,则阻止(tomcat)web应用程序启动



如何在web应用程序启动(Tomcat或其他(时设置"配置检查",如果不满足条件,则不应启动应用程序。

假设应用程序需要一个文件/tmp/demy存在于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:

在初始化web应用程序中的任何筛选器或servlet之前,将通知所有Servlet ContextListener上下文初始化。

例如:

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>

一个想法(但也可能有其他想法(是实现一个servlet,该servlet将执行此检查,并在条件为false时退出。您需要在上下文部署开始时使用适当的启动时加载标记来运行它。web.xml将看起来像:

<servlet>
<display-name>startup condition servlet</display-name>
<servlet-name>startup condition</servlet-name>
<servlet-class>com.xxx.yyy.ConditionChecker</servlet-class>
<load-on-startup>1</load-on-startup>
<init-param>
<param-name>FILE_TO_CHECK</param-name>
<param-value>/tmp/dummy</param-value>
</init-param>
</servlet>

当不满足条件(/tmp/demy不存在(时,此servlet可以执行System.exit(1)。请不要这样做会杀死Tomcat。并没有完全停止部署过程。如果有人想对此进行微调,你可以编辑我的帖子。

最新更新