Life Cycle of a Java Servlet

Introduction 

 
In this article, I will be discussing the lifecycle of a servlet. The lifecycle of a servlet is very simple. It executes three methods during its lifecycle. Those three methods are:
  1. init() method
  2. service() method
  3. destroy() method
But before these three methods run, there is something more that happens in the lifecycle of a servlet. 
 
First, when the container starts up, it reads the deployment descriptor of the web application and then finds the servlet class. Now the container can load the servlet class at the same moment or it can wait until the client request. It depends on the container. After that, the container creates an instance of the servlet class. Each time the client requests the servlet, a separate thread is created.
  
The various steps in the lifecycle of a servlet are:
  1. The Container loads the servlet class. 
    Servlet1.jpg
  2. The Container creates the object of the servlet class. The constructor that runs is the default constructor.  
    Servlet2.jpg  
  3. Now the container runs the init() method and passes the reference of servletconfig in it. The Init() method is executed only once during the lifecycle of a servlet.  
    Servlet3.jpg    
  4. Now the service() method is called by container. The Servlet spends most of its time in this method. The Service() method has doGet() and doPost() methods. One of the methods is executed on the basis of the client request. Each client request creates the separate thread of the servlet
    Servlet4.jpg
  5. After the service () method is completed, the destroy () method is called. It is also called only once during the lifecycle. The Destroy() method makes the servlet suitable for garbage collection.
     
    Servlet5.jpg       
I hope this article was useful to you and thank you for reading it.  


Similar Articles