Explain the life cycle of a Servlet.
Answered
Explain the life cycle of a Servlet.
Best answer
A Servlet is managedĀ through a well-defined life cycle that defines how it is loaded and instantiated, is initialized, handles requests from clients, and is taken out of service. This life cycle is expressed in the Servlet API by the init, service, and destroy methods of the javax.servlet.Servlet interface.
-
- Loading and InstantiationĀ – The servlet container is responsible for loading and instantiating servlets. The servlet container loads the servlet class using normal Java class loading facilities. The loading may happen when the servlet engine itself is started, or later when a client request is actually delegated to the servlet. After loading the Servlet class, the container instantiates it for use.
-
- InitializationĀ – After the servlet object is instantiated, the container will initialize the servlet before it can handle requests from clients. The container initializes the servlet instance by calling the init() method of the Servlet interface with a unique (per servlet declaration) object implementing the ServletConfig interface. In the init() method, the servlet can read configuration parameters using ServletConfig interface from the deployment descriptor or perform any other one-time activities, so the init() method is invoked once and only once by the servlet container.
-
- Request HandlingĀ – After a servlet is properly initialized, the servlet container may use it to handle client requests using the service() method of the Servlet interface. Requests are represented by request objects of type ServletRequest. The servlet fills out response to requests by calling methods of a provided object of type ServletResponse. These objects are passed as parameters to the service() method of the Servlet interface. In the case of an HTTP request, the objectsĀ are of types HttpServletRequest and HttpServletResponse.
End of ServiceĀ – When the servlet container determines that a servlet should be removed from service, it calls the destroy() method of the Servlet interface to allow the servlet to release any resources it is using and save any persistent state.