Stanley Mungai
Stanley Mungai

Reputation: 4150

Stop Servlet context from initializing in init method

I have a servlet which is loaded on server startup <load-on-startup>1</load-on-startup> in the init() method of the servlet I am checking for some parameter from a properties file. If the Parameter is not there, I want to stop the Entire Context from initializing.

public void init(){
   Readproperty pr = new ReadProperty();
     if(!pr.parameterExists()){
     //Edit: 
     throw new UnavailableException("Testing Stopping Context")

    }
}

What is the best way to do this? I do now want to Move this Code to my Context Listener Class so I am looking for the best way to do it from the `init()' method.

Upvotes: 1

Views: 2344

Answers (2)

Mark Thomas
Mark Thomas

Reputation: 16615

You can't stop a web application from starting from a servlet.

If you want to stop the web application from starting move your test(s) to a ServletContextListener. An exception in the contextInitialized() method will stop the web application from starting.

If you are using a recent Tomcat 7.0.x or 8.0.x release you can use a Tomcat specific option failCtxIfServletStartFails on the Context or Host that will cause the web application to fail if any of the load on startup servlets fail but this is non-standard. The ServletContextListener is the better option.

Upvotes: 4

AlexR
AlexR

Reputation: 115328

Just throw any exception there. Initialization will be aborted.

Upvotes: -3

Related Questions