Skip to main content

Servlet Life Cycle


Servlet Life Cycle 


The Servlet Life cycle can be defined as the entire process from it's creation till the destruction. The following are the are the path followed by the servlets

-> The servlet is initialized by calling the init() method .

-> The servlet called service method to handle client request

-> Then the servlet terminated by calling destroy() method

-> Finally servlet is garbage collected by the garbage collector of the JVM

Now let's consider the servlet life cycle  in detail

INIT() Method


The init() method designed to called only once. It is called when the servlet is created and not called over and over and again when the user is requested for the same servlet.

The init() method definition looks like this:

public void init() Throws ServletException{
 // write the initialization code here
}



The Service method


The service method is the main method which helps to perform the actual task .
The servlet container call the service method to handle the request coming from the client and write formatted response back to the client.

 Each time the server receive a request for a servlet the server create a new thread and call the service method .The service method check the HTTP request type (get,post,put,delete...) and call doGet ,doPost etc method as appropriate .
The service method looks like this:
public void service(ServletRequest request, 
                    ServletResponse response) 
      throws ServletException, IOException{
} 
The service method is called by the servlet container and service method invokes doGet ,doPost and so on so you
you have nothing to do with service() method .But you override either with doPost(), doGet() depending up on
what type of request you received from the client.doPost() and doGet() are most frequently use methods

destroy() Method

The destroy() method is called only once at the end of the life cycle. When this method is invokes it give a chanto
servlet to close database connection, enter cookies list, and things like that. After destroy() method
is invoked the servlet marked for garbage collection

the destroy() method look like this:

  public void destroy() {
    // Finalization code...
  }

Comments