Search code examples
servletsproduction-environmentjava-ee-7

Stop launch of web app from `ServletContextListener` method `contextInitialized`


I have implemented a ServletContextListener in a Java Servlet web app via the @WebListener annotation. In my contextInitialized method I do some set-up work and verify that expected resources are available.

If I determine in that contextInitialized method that something is wrong, how do I stop the web app from continuing onwards with executing servlets? Those servlets should not execute if the environment is not suitable (such as no database available).

How to gracefully handle a faulty environment for a servlets-based web app?


Solution

  • No, it appears that the ServletContextListener interface was not designed with the intent to be able to prevent the launch of a web app.

    As this Answer states, the Servlet spec says a ServletContextListener may somehow disable access to the web app when an Exception is encountered. That word may means optional, not required. Nor does the spec define exactly what stopping access to the web app means.

    Apparently the implemented behavior in various web containers varies widely. Some do nothing, some log it and move on, some prevent the web app from being deployed.

    My experience with Tomcat 8.0.33… Putting throw new RuntimeException ( "bogus stop servlet " ); in the contextInitialized method prevents the app from being deployed. The console during deployment in the IDE report reports “FAIL - Deployed application at context path / but context failed to start”. Unfortunately neither that console nor none of the logs capture the report of the actual Exception. So if you throw more than one Exception from one or more listeners, debugging will not be obvious.

    As mentioned elsewhere in Stack Overflow, the most reliable solution is probably to have your ServletContextListener mark success or failure with a flag variable stored in the servlet session. Then have your servlet code retrieve and examine that flag. Your servlet code would then determine the appropriate course of action. Your web app would be deployed, but your own servlet(s) could choose to do nothing and send back some HTTP error code.

    Similar questions:

    Side note: When adding or editing your ServletContextListener you may need to do a 'clean-and-build' operation on your project. Your IDE’s hot-swap or deploy-while-developing feature may not pickup on a new or changed listener. Trace your code or do some logging to verify.