Servlet Life Cycle

In this tutorial, we will explore the servlet life cycle and demonstrate its stages using a simple example. A servlet goes through several stages, managed by the servlet container, from its creation to its destruction.

Introduction

A servlet's life cycle consists of the following stages:

  1. Loading and Instantiation: The servlet class is loaded and an instance of the servlet is created.
  2. Initialization (init method): The servlet is initialized and prepared to handle requests.
  3. Request Handling (service method): The servlet processes client requests.
  4. Destruction (destroy method): The servlet is taken out of service and its resources are cleaned up.

We'll create a LifecycleServlet to illustrate these stages.

Project Structure

Here's the structure of our project:

servlet-lifecycle-example/
├── src/
│   ├── main/
│   │   ├── java/
│   │   │   └── com/
│   │   │       └── example/
│   │   │           └── servlet/
│   │   │               └── LifecycleServlet.java
│   │   ├── resources/
│   │   └── webapp/
│   │       ├── WEB-INF/
│   │       └── index.jsp
└── pom.xml

Maven Dependencies

Add the following dependencies to your pom.xml:

<dependencies>
    <!-- Servlet API -->
    <dependency>
        <groupId>jakarta.servlet</groupId>
        <artifactId>jakarta.servlet-api</artifactId>
        <version>6.1.0</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

Creating the Servlet

Let's create a LifecycleServlet that extends the HttpServlet class and demonstrates the servlet life cycle methods.

LifecycleServlet.java

package com.example.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/lifecycle")
public class LifecycleServlet extends HttpServlet {

    @Override
    public void init() throws ServletException {
        // Servlet initialization code
        System.out.println("LifecycleServlet initialized.");
    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Request handling code
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html><body>");
        out.println("<h1>LifecycleServlet at your service</h1>");
        out.println("</body></html>");
        System.out.println("LifecycleServlet service method called.");
    }

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

Explanation of Servlet Methods

init()

  • Purpose: The init method is called once when the servlet is first initialized. It is used to perform any servlet-specific initialization tasks.
  • Example in LifecycleServlet: The init method logs a message indicating that the servlet has been initialized.

service(HttpServletRequest request, HttpServletResponse response)

  • Purpose: The service method is called for each request to the servlet. It determines the type of request (GET, POST, etc.) and dispatches it to the appropriate handler method (doGet, doPost, etc.).
  • Example in LifecycleServlet: The service method responds with a simple HTML message and logs a message indicating that the service method was called.

destroy()

  • Purpose: The destroy method is called once when the servlet is about to be destroyed. It is used to perform any cleanup tasks.
  • Example in LifecycleServlet: The destroy method logs a message indicating that the servlet has been destroyed.

Creating the JSP

Create a simple JSP page to test the LifecycleServlet.

index.jsp

<!DOCTYPE html>
<html>
<head>
    <title>Servlet Life Cycle</title>
</head>
<body>
    <h1>Servlet Life Cycle</h1>
    <form action="lifecycle" method="get">
        <input type="submit" value="Call LifecycleServlet">
    </form>
</body>
</html>

Running the Application

  1. Build your project with Maven:
    mvn clean install
    
  2. Deploy the WAR file to your servlet container (e.g., Apache Tomcat).
  3. Access the application at http://localhost:8080/servlet-lifecycle-example.

Conclusion

In this tutorial, we demonstrated the servlet life cycle stages using a LifecycleServlet example. We covered the init, service, and destroy methods, explaining their purpose and how they are used in the servlet life cycle.

References

Related Servlet Posts

Comments