Life cycle of a servlet contains the following stages:
Following figure illustrates the life cycle of a servlet:
In this stage the servlet container searches the web.xml file for servlet. If the servlet is found, it will create an object for the corresponding servlet class in the memory. Servlet container can search for the servlet file in the local disk (in server) or in a remote location.
After instantiation of the servlet, the servlet container initializes the servlet object. Servlet container invokes the init(ServletConfig) method on the servlet object. This stage may raise ServletException or UnavailableException.
After initialization, servlet container creates the objects of HTTPServletRequest and HTTPServletResponse and invokes the service(request, response) method to serve the request of the client. This stage may raise UnavailableException or IOException.
A servlet is destroyed (unloaded) in the following cases:
- When the context is unloaded (server shutdown).
- When the service() method throws UnavailableException.
When the container decides to destroy the servlet, it allows all the current running threads to complete and stop any further requests. Finally destroy() method is invoked.
Note: In the servlet life cycle, init() and destroy() execute only once and service() method executes multiple times.
Above video demonstrates life cycle of a servlet using Eclipse IDE.