How to destroy a servlet before creation?

I was asked in an interview, how do you stop a Servlet from creating an instance of a servlet object?
I said that the container decides to destroy the servlet object.

He again said that the container would first create a servlet object and then destroy it. My question is, the servlet object has not yet been created, so there is no point in destroying it. How will you encode the servlet class when it tries to create its own trap in a serious problem, and our code (or in some other way) should stop it from being instantiated?

+4
source share
3 answers

You can stop the container from creating an instance of a servlet in three ways:

  • Remove the servlet link in web.xml. If your container processes annotations, you must also delete the @WebServlet annotation.

  • In the constructor, throw an exception.

  • In the init () method, throw an exception.

+1
source

I think it expects you to throw javax.servlet.UnavailableException from init()

public class UnavailableException extends ServletException This exception indicates that the servlet is unavailable. Servlets can report this exception at any time, and the network service running the servlet must behave appropriately. There are two types of inaccessibility, and complex services will deal with this in different ways:

Permanent unavailability. The servlet will not be able to process client requests until some administrative action is taken to fix the servlet problem. For example, the servlet may not be configured correctly or the state of the servlet may be corrupted. Well-written servlets will record both the error and the corrective actions that the administrator must take to allow the servlet to become available.

Temporary unavailability. The servlet cannot process requests at the moment due to a system-wide problem. For example, a third-tier server may not be available, or there may not be enough memory or disk storage to process requests. The problem can be fixed independently, for example, due to excessive workload, or, perhaps, the administrator should take corrective actions.

+1
source

You are right, the container is responsible for creating the servlets and the life cycle. First, it creates an instance of the servlet using the default public constructor, and then calls its init() method. When the container wants to destroy the servlet, it calls its destroy() method, which is usually (IMHO) empty.

The container can destroy first and then create a new servlet during hot redeployment when you deploy, probably a new version of your application. This is probably what your interviewer wanted to hear about.

0
source

All Articles