Life Cycle of Servlets

Servlets Life Cycle

  • The life cycle is the process from the construction till the destruction of any object.
  • A servlet also follows a certain life cycle.
  • The life cycle of the servlet is managed by the servlet container.
The container performs the following steps:
1. Loads Servlet Class
2. Creates instance of Servlet
3. Calls init( ) method
4. Calls service( ) method
5. Calls destroy( ) method

Architecture Diagram

servlet life cycle

1. Loads the Servlet Class

The classloader is responsible to load the Servlet class into the container. The servlet class is loaded when the first request comes from the web container.

2. Creates instance of Servlet

After loading of Servlet class into the container, the web container creates its instance. The instance of Servlet class is created only once in the servlet life cycle.

3. Calls the init( ) method

The init( ) method performs some specific action constructor of a class. It is automatically called by Servlet container. It is called only once through the complete servlet life cycle.

Syntax:
public void init(ServletConfig config ) throws ServletException

4. Calls the service( ) method

The service( ) method performs actual task of servlet container. The web container is responsible to call the service method each time the request for servlet is received. The service( ) invokes the doGet( ), doPost( ), doPut ( ), doDelete( ) methods based on the HTTP request.

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

5. Calls the destroy( ) method

The destroy( ) method is executed when the servlet container remove the servlet from the container. It is called only once at the end of the life cycle of servlet.

Syntax:
public void destroy( )