Life cycle of a Servlet: Understanding Its Journey

Hello everyone! After our discussion on what Servlets are and how they surpass CGI, a crucial next step is to understand their dynamic journey within a web application. This involves exploring the Life cycle of a Servlet, which defines the various stages a Servlet undergoes from its loading into memory until its eventual removal. A Servlet’s lifecycle is meticulously managed by the Servlet container, ensuring efficient resource utilization and proper handling of client requests.

Stages in the Servlet Lifecycle

The life cycle of a Servlet comprises three main stages, each managed by the Servlet container (like Apache Tomcat):

  1. Initialization Stage (init() method)
  2. Request Handling Stage (service() method)
  3. Destruction Stage (destroy() method)

A Servlet instance is created only once when the Servlet container first loads it, typically upon the first request for that Servlet or when the server starts if configured to do so. This single instance handles all subsequent client requests, which improves efficiency significantly.Diagram illustrating the complete life cycle of a Servlet, showing the initialization, request handling, and destruction phases

1. Initialization Stage: The init() Method

The initialization stage marks the beginning of a Servlet’s life. When the Servlet container loads a Servlet for the first time, it invokes the init() method. This method is called only once throughout the Servlet’s lifetime, immediately after the Servlet is instantiated and before it starts handling any client requests.

The primary purpose of the init() method is to perform one-time initialization tasks that are required for the Servlet to function correctly. This often includes:

  • Establishing database connections.
  • Loading configuration parameters or resources.
  • Initializing expensive objects that will be reused across multiple requests.

Signature of the init() method:

Java

 
public void init(ServletConfig config) throws ServletException

or (more commonly for HttpServlet):

Java

 
public void init() throws ServletException

The ServletConfig object, passed to the init(ServletConfig config) method, allows the Servlet to access configuration information specified in the deployment descriptor (web.xml). For instance, you can retrieve initialization parameters unique to that Servlet here.

2. Request Handling Stage: The service() Method

Following successful initialization, the Servlet enters the request handling stage. For every subsequent client request that targets the Servlet, the Servlet container invokes the service() method. This method acts as the core of the Servlet, where the actual processing of client requests occurs.

The service() method receives two crucial objects as parameters:

  • ServletRequest: This object encapsulates all information about the client’s request, such as parameters, headers, input streams, and client details.
  • ServletResponse: This object allows the Servlet to send a response back to the client, including setting response headers, status codes, and writing the actual content (e.g., HTML, plain text) to the client’s browser.

Signature of the service() method:

Java

 
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException

For HTTP Servlets (HttpServlet), the generic service() method is typically overridden by the HttpServlet class itself. It dispatches the request to more specific HTTP-method-based handler methods, such as doGet(), doPost(), doPut(), or doDelete(), based on the HTTP method of the client’s request. Most commonly, you will override doGet() for GET requests and doPost() for POST requests in your Servlets.

3. Destruction Stage: The destroy() Method

The final stage in the Servlet lifecycle is destruction. When the Servlet container decides to remove a Servlet from service (e.g., when the application is undeployed, the server is shut down, or the Servlet is no longer needed), it invokes the destroy() method. Like init(), this method is called only once throughout the Servlet’s lifetime, just before the Servlet instance is garbage collected.

The primary purpose of the destroy() method is to perform cleanup activities and release any resources that the Servlet might have acquired during its operation. Common cleanup tasks include:

  • Closing database connections.
  • Saving persistent state.
  • Releasing file handles or other system resources.

Signature of the destroy() method:

Java

 
public void destroy()

By properly implementing the destroy() method, developers can ensure that resources are released efficiently, preventing memory leaks and maintaining the stability of the web server.

Understanding the Servlet Hierarchy

To effectively manage the Servlet lifecycle, it’s important to understand the class hierarchy involved:

  • javax.servlet.Servlet (Interface): This is the root interface for all Servlets. It declares the init(), service(), and destroy() methods.
  • javax.servlet.GenericServlet (Abstract Class): This class provides a basic implementation of the Servlet interface and ServletConfig interface. It handles common tasks but is protocol-independent. You can extend this for non-HTTP protocols.
  • javax.servlet.http.HttpServlet (Abstract Class): This is the most commonly used abstract class for building web applications. It extends GenericServlet and provides HTTP-specific methods like doGet(), doPost(), doPut(), doDelete(), etc. When you override doGet() or doPost(), you’re effectively providing the logic for the service() method’s dispatch to these specific handlers.

By following this well-defined lifecycle, Servlets ensure that resources are managed efficiently, and requests are processed reliably, forming the backbone of dynamic web applications. Therefore, a clear grasp of this lifecycle is fundamental for every Java web developer.