Matt Felzani
Matt Felzani

Reputation: 795

Is it possible to make a Java Servlet Exception prevent an application from starting?

I have a Java Servlet that's marked at load-on-startup and have implemented init(). As part of the init() logic there's a call to validate() which determines if things are, well, valid.

My issue is that if the validate() determines things are not okay I want to prevent the app from starting as an alert that something needs to be fixed. I tried throwing a ServletException and while that piped info out to my console I was still able to send traffic at the app and it responded.

Lastly, my hands are somewhat tied with the timing. My servlet extends a base class which sets up the content that I'm trying to validate.

If there is a solution I'd need it to run on Tomcat and WebLogic.

Upvotes: 4

Views: 1445

Answers (1)

Agustí Sánchez
Agustí Sánchez

Reputation: 11223

As pointed out by Luiggi Mendoza above, the proper place for web application-wide initialization is in a ServletContextListener rather than relying on the init method of an individual servlet.

The web application context is destroyed (at least in Tomcat 6) when an exception (runtime exception) is thrown from a listener's contextInitialized method.

Your best bid is to move the initialization logic to a ServletContextListener (you can define multiple listeners per web application and they're executed in the order they are registered in web.xml). And keep in the servlet only the request processing logic.

Upvotes: 3

Related Questions