Explain the life cycle of a Servlet.
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.