Life Cycle of a Servlet

The Servlet Container is responsible for maintaining the life cycle of a Servlet. The life cycle has the below following phases.

  1. Load Servlet Class
  2. Servlet instance is created
  3. init() method is invoked
  4. service() method is invoked
  5. destroy() method is invoked

Load Servlet Class

The servlet class is loaded when the first request for the servlet is received by the web container. The classloader is responsible for loading the servlet class.

Servlet instance is created

Once the Servlet class is loaded the Web Container creates the instance of it. Servlet instance will be created only once in the life cycle.

init() method is invoked

The Web container calls the init() method after creating the servlet instance, the init() method is used to initialize the servlet. Below is the signature of the init() method

public void init(ServletConfig config) throws ServletException

service() method is invoked

The Web Container calls the service() method each time when the request for the servlet is received. when a request is received the server creates a new thread and calls the service() method. The service() method checks the HTTP request type (GET, POST, PUT, DELETE) and calls the appropriate doGet(), doPost(), doPut(), doDelete() methods. The Signature of the service() method is given below.

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

destroy() method is invoked

The destroy() method is called only once at the end of the life cycle of the servlet. This method gives the servlet an opportunity to do clean up of the resources such as closing the database, thread, etc. The signature of the destroy() method is given below

public void destroy()

Leave a Reply

Your email address will not be published. Required fields are marked *