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:
- init() method
- service() method
- 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:
- The Container loads the servlet class.
- The Container creates the object of the servlet class. The constructor that runs is the default constructor.
- 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.
- 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
- 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.
I hope this article was useful to you and thank you for reading it.