Today, I will explain Life Cycle of a Servlet using a code example.
The lifecycle of a servlet refers to the sequence of events that occur from the moment a servlet is loaded into memory by the servlet container (e.g., Tomcat) to the point where it is removed or destroyed. Understanding the servlet lifecycle is crucial for developers because it allows them to manage resources and perform necessary setup and cleanup tasks at the right moments.
Overview of Servlet Life Cycle Stages
- Loading and Instantiation. When a web application is deployed or started, the servlet container locates and loads servlet classes specified in the web.xml configuration or using annotations. During this phase, the servlet class is instantiated by calling its constructor.
- Initialization (
init()
method). After instantiation, the servlet container calls theinit()
method to perform one-time initialization tasks. Developers can override this method to set up resources like database connections, read configuration files, or initialize variables. Theinit()
method is executed only once during the lifecycle of a servlet.
@Override
public void init() throws ServletException {
// Initialization code goes here
}
- Request Handling (
service()
method). The servlet container handles incoming client requests by calling theservice()
method. This method receivesHttpServletRequest
andHttpServletResponse
objects and delegates the request to the appropriate HTTP method-specific handler method (doGet()
,doPost()
, etc.). Theservice()
method is responsible for determining which HTTP method was used and dispatching the request accordingly.
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Request handling code goes here
}
- HTTP Method-Specific Handling (
doGet()
,doPost()
, etc.). Depending on the HTTP method of the incoming request, the servlet container calls the corresponding HTTP method-specific handler method. Developers must override these methods to provide custom request processing logic. For example, if you want to handle GET and POST requests differently, you would overridedoGet()
anddoPost()
.
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Handling GET requests
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Handling POST requests
}
- Request Cleanup: After the request has been processed and the response has been generated, the servlet container sends the response back to the client. Any resources, such as database connections or open files, should be closed during this phase to prevent resource leaks.
- Destruction (
destroy()
method): When the servlet container decides to unload or remove a servlet (typically during web application shutdown or when the servlet is no longer needed), it calls thedestroy()
method. This method is used for cleanup tasks like closing database connections, releasing resources, or performing any other necessary shutdown operations.
@Override
public void destroy() {
// Cleanup code goes here
}
Code Example to Demonstrate Servlet Lifecycle Methods
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class MyServlet extends HttpServlet {
@Override
public void init() throws ServletException {
// Initialization code goes here (executed once)
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Handling GET requests
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Handling POST requests
}
@Override
public void destroy() {
// Cleanup code goes here (executed once)
}
}
In this example, the servlet MyServlet
overrides the init()
, doGet()
, doPost()
, and destroy()
methods to demonstrate the servlet’s lifecycle. The init()
method can be used for one-time setup, doGet()
and doPost()
for request handling, and destroy()
for cleanup tasks. Keep in mind that this is a simplified example, and real-world servlets may have more complex logic and may interact with databases, external services, or other resources.