Alex Vayda
Alex Vayda

Reputation: 6494

How to stop the entire java webapp when the servlet fails to initialize

I want my web application to fail on startup if any of my servlet fails to initialize. I would expect if I throw an exception form the Servlet.init() method it would cause the entire app to fail, but apparently it doesn't. The web container (Tomcat 7 in my case) just fails to load that particular servlet, but the application is reported to be successfully deployed anyway.

It behaves as expected if an exception thrown from e.g. ServletContextListener.contextInitialized() method, but why the exception thrown from the Servlet.init() doesn't have this effect?

Is there any way to stop the application in case of a Servlet initialization error?

Upvotes: 2

Views: 2072

Answers (1)

Ramesh PVK
Ramesh PVK

Reputation: 15446

Try this following steps:

  1. Keep your servlet in load-on-startup list such that your servlet is initialized on application start.
  2. In Servlet.init() method, set an attribute in ServletContext saying the servlet is initialzied. ex, myServletInited
  3. Implement ServletContextListener.contextInitialzied() method. Check if myServletInited is present. If is does not present throw an exception which fails the application.

Upvotes: 3

Related Questions