Introduction
Life cycle of a servlet contains the following stages:
- Instantiation
- Initialization
- Servicing
- Destruction
Following figure illustrates the life cycle of a servlet:
Instantiation
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.
Initialization
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.
Servicing
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.
Destruction
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.
Video: http://www.startertutorials.com/ajwt/servlet-life-cycle.html
Above video demonstrates life cycle of a servlet using Eclipse IDE.
Suryateja Pericherla, at present is a Research Scholar (full-time Ph.D.) in the Dept. of Computer Science & Systems Engineering at Andhra University, Visakhapatnam. Previously worked as an Associate Professor in the Dept. of CSE at Vishnu Institute of Technology, India.
He has 11+ years of teaching experience and is an individual researcher whose research interests are Cloud Computing, Internet of Things, Computer Security, Network Security and Blockchain.
He is a member of professional societies like IEEE, ACM, CSI and ISCA. He published several research papers which are indexed by SCIE, WoS, Scopus, Springer and others.
Leave a Reply