Search code examples
tomcatweb-applicationsstartup

Prevent (tomcat) web application from starting if configuration incomplete


How do I set a "configuration check" on a web application startup (Tomcat or other) and if the condition is not met the application should not start.

Let's say the application require a the file /tmp/dummy to exist on the fs in order to start. So I have something like

public class TestConfig {

    public static void TestServerConfiguration()  {
        if (! new File("/tmp/dummy").exists()) {
            // don't start this web application ... 
        }
    }

}

Where should I include this test?

Thanks!


Solution

  • I would go with a ServletContextListner. As with the servlet answer, it will not stop Tomcat but it will prevent the web application from loading. One advantage over the servlet answer is from the Javadoc:

    All ServletContextListeners are notified of context initialization before any filters or servlets in the web application are initialized.

    As an example:

    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) {
        }
    }
    

    Above assumes that your web.xml specifies a Servlet 3.0 or above environment (or that you don't have a web.xml at all):

    <?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>
    

    If you're using a lower servlet spec then you'll want to remove the @WebListener annotation and declare the listener in web.xml:

    <web-app ...>
       <listener>
        <listener-class>
                 com.example.package.name.FileVerifierContextListener 
            </listener-class>
       </listener>
    </web-app>