Servlet Life Cycle
Servlet container manages life cycle of a servlet. And it does following things as part of servlet life cycle:
- Loading the servlet class
- Creating the servlet instance (object)
- Calling the init() method for initialization
- Calling the service() method to serve the incoming requests
- Calling the destroy() method before destroying the servlet object
Servlet object’s life cycle is managed by the Servlet container (also called web server).
1. Loading the Servlet class
As the first stage of servlet life cycle, the servlet container loads the servlet class. The loading process can happen in two ways: 1. Early loading, 2. Lazy Loading
- Early Loading : The Servlet is loaded by the servlet container while initializing the context
- Lazy Loading : In this case, the servlet is not loaded while initializing. But when the servlet container determines that there are requests for the servlet to respond, then it loads the servlet. It is known as lazy loading.
2. Instantiating the Servlet
As the next step, the servlet is instantiated, meaning object is created.
3. Call init() method
In this step, init() method of javax.servlet.Servlet is invoked and any initialization code written inside it is executed. This method is used to set any initialization parameters in the servlet.
Note -> init() is called only once in the life cycle of a servlet
public void init(ServletConfig config) throws ServletException
4. Call service() method
Till this point, the servlet is ready to serve client requests. Whenever a request comes in for the servlet, it processes it by calling its service() method.
Note -> service() is called as many times as many requests come in for the servlet
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException
5. Call destroy() method
When a Servlet container determines to destroy/unload the Servlet, it performs the following operations,
- It allows all the threads currently running in the service method of the Servlet instance to complete.
- The Servlet container calls the destroy() method on the Servlet instance to do any cleanup activity like closing database connections.
After the destroy() method completes its execution, the Servlet container releases all the references of the Servlet object so that it becomes eligible for garbage collection.
public void destroy()