Wednesday, 16 September 2009

Terminating a Servlet

I needed to terminate a Java Servlet recently if a startup condition failed - my initial approach was:

System.exit(-1)

However, this terminates the entire servlet-container (Jetty, Tomcat, Glassfish, etc) together with any other servlets that may be running within. What I wanted was to just terminate the servlet in question...

As usual, the answer is relatively straightforward - you need to throw a servlet exception - at first glace this can be achieved using javax.servlet.ServletException.

The servlet-container will catch this exception and gracefully terminate the servlet without affecting any other running servlets.

However, there is also an UnavailableException (a subclass of ServletException) that is more appropriate for indicating mis-configuration, etc. Interestingly, this class can be used to indicate both 'permanent' and 'temporary' unavailability, with permanent unavailability meaning that the servlet cannot recover.

If an permanent UnavailableException is thrown during the init() method, the servlet will never enter into service. Alternatively, if the exception is thrown during normal processing, the servlet-container will remove that servlet instance and create a new one in its place.

If a temporary UnavailableException is thrown the servlet-container will generate a HTTP 503 message, with the Retry-After header set to indicate to the client how long the service is likely to be unavailable for. Note that thowing a 'temporary' UnavailableException during the init() method prevents the servlet from entering into service - as with a 'premanent' exception above.

In my case I wanted to indicate 'permanent' unavailability, which is based on the following snippet:

import javax.servlet.*

if (true) {
throw new UnavailableException("Startup condition failed")
}

0 comments:

Post a Comment