Life cycle of Servlet

In this article, we will discuss the Life cycle of the servlet. The life cycle of a servlet means series of changes servlet passes through its from beginning till the end.

What is the Servlet Life Cycle?

In order to understand Servlet before, let us see the Life cycle of it. Everything in Servlet is managed by the Servlet Container. Servlet Container is a part of a web server that interacts with the servlet. This is the main component of the server that manages the life cycle of the servlet.

What is a Servlet Container?

The container here means a servlet engine that is usually provided by the server within which the servlet runs.

  • The servlet classes generally interact with the server via an HTTP request/response mechanism implemented by the servlet engine i.e Servlet Container.
  • The main function of the container is to contain servlet classes and manage their life cycle.
  • Apart from supporting the HTTP protocol, the servlet container also supports request/response based protocols, such as HTTPS, for more secure network interaction.

Stages involved in Servlet Life Cycle:

  • Loading
  • Initializing.
  • Handle request
  • Destroy

Loading a Servlet

This is the first step involved in the lifecycle where the servlet container loads and initializes the Servlet. This  happens in either of the two steps below:

  • The context here is initialized to zero or some positive integer value
  • Sometimes the servlet container/web container may delay the servlet request for initialization if it is not in the service stage.

Here Servlet container performs two major operation

  • Loading of the servlet class
  • Instantiating a servlet with the no-argument constructor.

Instantiating a Servlet

The Servlet container initializes the object of the servlet with servlet.init(). An instance of this servlet class is created only once.

Handling Request

Whenever the request is received the web container invokes the service() method. The service() method then handles the request and may throw exceptions like servlet exception, IOException.

Destroy Servlet

Before removing the servlet instance, the web container invokes the destroy() method. It is done so that any thread inside it can complete its job and can be released.

How Servlet Works?

Now let us see how our servlet works. As we know everything in the servlet is handled by the servlet container or we can say web container.

  • First, it loads the Servlet class that we will create
  • Instances of the servlet class will be created (as we know it will be created only once).
  • Then, it will call the init() method.
  • Then, it will call the service() method by passing request and response objects.

If the web container wants to remove the servlet it will call the destroy() method.

Following is the architectural view of the Life cycle of Servlet.

Methods in Life Cycle of a Servlet:

init() method:

This method is called by the web container to instantiate the servlet class. This method is called only once in the lifetime of the servlet. When a client calls a servlet, it gets instantiated with each user request get transformed a new thread inside the system and each is handed over to doGet() as well as doPost() methods. Following is the init() method definition.

/**

* @see Servlet#init(ServletConfig)

*/

public void init(ServletConfig config) throws ServletException {

// TODO Auto-generated method stub

}

service() method:

It handles the request and response object in Servlet. The servlet container calls the service() methods to handle requests and give responses. The main task of handling requests is done here. It is called multiple times in the life cycle. It checks whether the request is GET, POST, DELETE, and then called the required method like doGet(),doPost(), etc. Following is the definition of service() method.

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

// TODO Auto-generated method stub

}

destroy() method: 

It is run only once and indicates the removal of the servlet instance. Closing database connection, halt background thread, write cookies, etc is performed in the destroy() method. Following is the definition of destroy() method

public void destroy() {
// TODO Auto-generated method stub
}

Let’s see the sample example for the Life cycle of Servlet

import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class LifeCycleDemo
 */
@WebServlet("/LifeCycleDemo")
public class LifeCycleDemo extends HttpServlet {
  private static final long serialVersionUID = 1L;

  /**
   * @see HttpServlet#HttpServlet()
   */
  public LifeCycleDemo() {
    super();
    // TODO Auto-generated constructor stub
  }

  public void init(ServletConfig config) throws ServletException {
    // TODO Auto-generated method stub
    System.out.println("In initaialization");
  }

  /**
   * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse
   *      response)
   */
  protected void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    System.out.println("In service method");
  }
         /**
   * @see Servlet#destroy()
   */
  public void destroy() {
    // TODO Auto-generated method stub
    System.out.println("Servlet is Detroyed");
  }
}


Thus we have seen the Life cycle of Servlet – Initialization, service, and destruction in detail which ensures that the servlet manages the application resources efficiently. In the next article, we shall see what is the Client  Request and along with request what else is sent in the Request Header.