Advanced Java and Web Technologies for JNTUK
Blog providing beginner tutorials on different web technologies like HTML, CSS, Javascript, PHP, MYSQL, XML, Java Beans, Servlets, JSP and AJAX

02/10/2016 Categories: Servlets. No Comments on Life Cycle of a Servlet



Life cycle of a servlet contains the following stages:

  • Instantiation
  • Initialization
  • Servicing
  • Destruction


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.

Related Links:

Note: Do you have a question on this article or have a suggestion to make this article better? You can ask or suggest us by filling in the below form. After commenting, your comment will be held for moderation and will be published in 24-48 hrs.

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll Up