Servlet - Life Cycle

The lifecycle of a servlet is controlled by the container(Tomcat, Jetty etc) in which the servlet has been deployed. The life cycle contains the following steps:
 
 - Servlet Class is loaded.
 - Servlet Instance is created.
 - init() method.
 - service() method.
 - destroy() method.
 
 
Servlet Class is loaded:
Before a servlet can be invoked the servlet container must first load its class definition. This is done just like any other class is loaded.
 
Servlet Instance is created:
The web container creates the instance of a servlet after loading the servlet class. The servlet instance is created only once in the servlet life cycle.
 
init() method:
When a servlet instance is created, its init() method is invoked. The init() method allows a servlet to initialize itself before the first request is processed.
 

public void init(ServletConfig config) throws ServletException

 
service() method:
The web container calls the service method each time when request for the servlet is received. If servlet is not initialized, it follows the first three steps as described above then calls the service method. If servlet is initialized, it calls the service method. Notice that servlet is initialized only once. 
 

public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException

 
The service () method is called by the container and service method invokes doGe, doPost, doPut, doDelete, etc. methods as appropriate.
 
The doGet() Method:
You should use doGet() when you want to intercept on HTTP GET requests or not specify any method.
 

public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
     // Servlet code
}

 
 
The doPost() method:
You should use doPost() when you want to intercept on HTTP POST requests.
 

public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
     // Servlet code
}

 
 
 
destroy()  method:
When a servlet is unloaded by the servlet container, its destroy() method is called. This step is only executed once, since a servlet is only unloaded once.
A servlet is unloaded by the container if the container shuts down, or if the container reloads the whole web application at runtime.

public void destroy()

 

Note : init() method call inside service() method but it is not any sense. destroy() method call inside service() method as it is also a method like any other. This can make sense sometimes, as destroy() will do whatever logic you have defined (cleanup, remove attributes, etc.) .