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

标签 tomcat web-applications startup

如何在 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/

相关文章:

java - Java Web 应用程序的类似桌面的 UI 实现?

c# - 如何在 Startup.cs 文件中获取 ASP.NET MVC 应用程序的基本 url?

java - spring-boot 应用程序的外部配置

java - 关于我的错误,如何在 tomcat 中配置 jndi?

spring - 离线在服务器上部署Maven Spring Boot项目

java - 在 Eclipse Mars 中找不到 Tomcat Runtime

javascript - 如何在 iOS Web 应用程序上访问用户可缩放的缩放状态?

javascript - 在 React 网络应用程序中使 Redux 商店失效/刷新?

python - 在 IPython 启动时自动加载模块

iOS Present modal view controller 在启动时没有闪光灯