Servlet Lifecycle: A Complete Guide

Servlets are at the core of Java web applications, and understanding their lifecycle is essential for effective development. This guide explores the lifecycle methods (init(), service(), and destroy()) and the role of the web.xml configuration file in servlet deployment and initialization.

Servlet Lifecycle Methods

1. init() Method

The init() method is called once when the servlet is first loaded into memory. It is used to initialize resources required by the servlet.

Key Points:

  • Invoked when the servlet is instantiated.
  • Initializes the servlet for handling client requests.
  • Runs only once during the servlet’s lifecycle.

Example:

@Override
public void init() throws ServletException {
    super.init();
    System.out.println("Servlet is being initialized");
    // Initialize database connection or resources here
}

2. service() Method

The service() method is invoked for every client request to the servlet. It determines the type of request (e.g., GET or POST) and delegates to the corresponding method (doGet(), doPost()).

Key Points:

  • Processes client requests and generates responses.
  • Runs every time a request is received.

Example:

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String method = req.getMethod();
    if ("GET".equalsIgnoreCase(method)) {
        doGet(req, resp);
    } else if ("POST".equalsIgnoreCase(method)) {
        doPost(req, resp);
    }
    // Additional processing logic can go here
}

3. destroy() Method

The destroy() method is called when the servlet is taken out of service or the application is shutting down. It is used to release resources.

Key Points:

  • Invoked once, just before the servlet is unloaded.
  • Releases resources such as database connections or file handles.

Example:

@Override
public void destroy() {
    System.out.println("Servlet is being destroyed");
    // Close database connections or clean up resources here
}

Servlet Lifecycle Diagram

  +-----------------------------+
  |         Client Request      |
  +-----------------------------+
              |
              v
      Servlet Container
              |
      +----------------+
      |  init() Method  | <--------+
      +----------------+          |
              |                   |
      +----------------+          |
      |  service() Method |       |
      +----------------+          |
              |                   |
      +----------------+          |
      |  destroy() Method | ------+
      +----------------+

The Role of web.xml Configuration File

The web.xml file is an essential deployment descriptor in Java EE applications. It defines how servlets are mapped and configured in the application.

Key Components in web.xml

Servlet Declaration:
Maps a servlet to a URL pattern.

<servlet>
    <servlet-name>ExampleServlet</servlet-name>
    <servlet-class>com.example.MyServlet</servlet-class>
</servlet>

Servlet Mapping:
Specifies the URL pattern that triggers the servlet.

<servlet-mapping>
    <servlet-name>ExampleServlet</servlet-name>
    <url-pattern>/example</url-pattern>
</servlet-mapping>

Initialization Parameters:
Defines parameters to be read by the servlet during initialization.

<init-param>
    <param-name>configValue</param-name>
    <param-value>12345</param-value>
</init-param>

Example web.xml File:

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         version="3.1">
    <servlet>
        <servlet-name>MyServlet</servlet-name>
        <servlet-class>com.example.MyServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>MyServlet</servlet-name>
        <url-pattern>/myServlet</url-pattern>
    </servlet-mapping>
</web-app>

Best Practices

  • Resource Management: Always release resources in the destroy() method.
  • Efficient Initialization: Use the init() method wisely for tasks like database connections.
  • Avoid Heavy Logic in service(): Delegate complex operations to helper classes for maintainability.
  • Annotations: Use annotations like @WebServlet for simple configurations instead of web.xml in modern applications.