Open In App

Life Cycle of a Servlet

Last Updated : 07 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The entire life cycle of a Servlet is managed by the Servlet container, which uses the jakarta.servlet.Servlet interface to understand the Servlet object and manage it. So, before creating a Servlet object, let's first understand the life cycle of the Servlet object, which is actually understanding how the Servlet container manages the Servlet object.

Note: If you have worked with a servlet before, you must have used import javax.servlet.*; but with Jakarta EE 9, the package names changed to import jakarta.servlet.*;

States of the Servlet Life Cycle

State-of-sevlet-life-cycle

The Servlet life cycle mainly goes through four stages, which is explained below:

1. Loading a Servlet

The first stage of the Servlet lifecycle involves loading and initializing the Servlet. The Servlet container performs the following operations:

  • Loading: The Servlet container loads the Servlet class into memory.
  • Instantiation: The container creates an instance of the Servlet using the no-argument constructor.

The Servlet container can load the Servlet at one of the following times:

  • During the initialization of the web application (if the Servlet is configured with a zero or positive integer value in the deployment descriptor).
  • When the Servlet is first requested by a client (if lazy loading is enabled).

2. Initializing a Servlet

After the Servlet is instantiated, the Servlet container initializes it by calling the init(ServletConfig config) method. This method is called only once during the Servlet's life cycle.

3. Handling request

Once the Servlet is initialized, it is ready to handle client requests. The Servlet container performs the following steps for each request:

  • Create Request and Response Objects
    • The container creates ServletRequest and ServletResponse objects.
    • For HTTP requests, it creates HttpServletRequest and HttpServletResponse objects.
  • Invoke the service() Method
    • The container calls the service(ServletRequest req, ServletResponse res) method.
    • The service() method determines the type of HTTP request (GET, POST, PUT, DELETE, etc.) and delegates the request to the appropriate method (doGet(), doPost(), etc).

4. Destroying a Servlet

When the Servlet container decides to remove the Servlet, it follows these steps which are listed below

  • Allow Active Threads to Complete: The container ensures that all threads executing the service() method complete their tasks.
  • Invoke the destroy() Method: The container calls the destroy() method to allow the Servlet to release resources (e.g., closing database connections, freeing memory).
  • Release Servlet Instance: After the destroy() method is executed, the Servlet container releases all references to the Servlet instance, making it eligible for garbage collection

Servlet Life Cycle Methods

There are three life cycle methods of a Servlet:

  • init()
  • service()
  • destroy()
Life-Cycle-of-Servlet

Servlet life cycle can be defined as the stages through which the servlet passes from its creation to its destruction.
The servlet life cycle consists of these stages:

  • Servlet is created
  • Servlet is initialized
  • Servlet is ready to service
  • Servlet is servicing
  • Servlet is not ready to service
  • Servlet is destroyed

1. init() Method

This method is called by the Servlet container to indicate that this Servlet instance is instantiated successfully and is about to put into the service.

Illustration:

// init() method

public class MyServlet implements Servlet {

public void init(ServletConfig config)

throws ServletException

{

// initialization code

}

// rest of code

}

Important Key Points about init() Method

A Servlet life begins from this method. This method is called only once to load the servlet, Since it is called only once so the connected architecture code is written inside it because we only want once to get connected with the database

Now the Question Arises Why can't we write connected architecture code inside the constructor, since constructor also run only once in it's entire life?

Ans: Suppose if the connection doesn't get established, then we can throw an exception from init() and the rest of the steps stop executing. But in the constructor we can't use, throw in it's prototype otherwise it is an error

  • This method receives only one parameter, i.e ServletConfig object.
  • This method has the possibility to throw the ServletException.
  • Once the servlet is initialized, it is ready to handle the client request.
  • In servlet programs, we use non parameterized version of init().

Now the Ouestion Arises Why it is recommended to use the non parameterized version of init() instead of parameterized version?

Ans: There are two approaches in order to answer this question. We are going to discuss about both the approach one by one.

Approach 1: Using the Parameterized init(ServletConfig.con)

When the parameterized init(ServletConfig con) is called during the servlet life cycle, the following steps occur:

  • First the overridden init(ServletConfig con) in our servlet class is executed.
  • Then the init(ServletConfig con) method in the parent HttpServlet class is called using super.init(con).
  • Finally the init() (non-parameterized version) in the parent HttpServlet class is invoked. However, this method has an empty body, making the call redundant.

public void init(ServletConfig con) throws ServletException

{

super.init(

con); // Calls HttpServlet's init(ServletConfig)

// Custom database connection code here

}

Disadvantages:

  • More Calls: Total 3 init() calls
    • Parameterized init(ServletConfig con) in our servlet class.
    • Parameterized init(ServletConfig con) in HttpServlet.
    • Non-parameterized init() in HttpServlet(empty body, hence useless)
  • Performace Overhead: Extra calls increase stack usage and execution time.

Approach 2: Using the Non-Parameterized init()

  • Instead of overriding the parameterized init(servletConfig con), override the non-parameterized init().
  • During the servlet life cycle
    • The parameterized init(servletConfig con) in theHttpServlet class is called automatically.
    • This method then calls the non-parameterizedinit() method of our servlet directly.

public void init() throws ServletException

{

// Custom database connection code here

}

Advantages:

  • Fewer Calls: Total of 2 init() calls
    • Parameterized init(ServletConfig con) in HttpServlet.
    • Non-parameterized init() in our servlet class.

2. service() Method

This method is used to inform the Servlet about the client requests

  • This method uses ServletRequest object to collect the data requested by the client
  • This method uses ServletResponse object to generate the output content

Illustration:

// service() method

public class MyServlet implements Servlet {

public void service(ServletRequest req,

ServletResponse res)

throws ServletException, IOException

{

// request handling code

}

// rest of code

}

Important Key Points about service() Method:

  • This method provides the connection between client and server
  • The web server calls the service() method to handle requests coming from the client( web browsers) and to send response back to the client
  • This method determines the type of Http request (GET, POST, PUT, DELETE)
  • This method also calls various other methods such as doGet(), doPost(), doPut(), doDelete()
  • This method accepts two parameters.
    • req is the ServletRequest object which encapsulates the connection from client to server
    • res is the ServletResponse object which encapsulates the connection from server back to the client

3. destroy() Method

This method runs only once during the lifetime of a Servlet and signals the end of the Servlet instance

Syntax:

// destroy() method

public void destroy()

{

// code

}

As soon as the destroy() method is activated, the Servlet container releases the Servlet instance

Important Key Points about destroy() Method:

  • The destroy() method is called only once.
  • It is called at the end of the life cycle of the servlet.
  • This method performs various tasks such as closing connection with the database, releasing memory allocated to the servlet, releasing resources that are allocated to the servlet and other cleanup activities.
  • After destroy() method the Servlet instance becomes eligible for garbage collection.

Java Servlet Example

Below is a sample program to illustrate Servlet in Java.

Java
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import java.io.*;

public class AdvanceJavaConcepts extends HttpServlet {
    private final String output; // Immutable (thread-safe)

    @Override
    public void init() throws ServletException {
        output = "Advance Java Concepts";
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
        throws ServletException, IOException {
        resp.setContentType("text/html");
        try (PrintWriter out = resp.getWriter()) {
            out.println(output); // Thread-safe
        }
    }

    @Override
    public void destroy() {
        System.out.println("Servlet destroyed");
    }
}

Article Tags :
Practice Tags :

Similar Reads