Phases of the Servlet Life Cycle
A servlet life cycle is managed by the servlet container (like Tomcat, Jetty, etc.), which is responsible for loading, initializing, and managing the servlet instances. There are mainly three phases in the servlet life cycle:
![What are the phases of servlet life cycle? servlet life cycle](https://www.testpreparationz.com/wp-content/uploads/2024/10/image-13-1-1024x585.png)
Table of Contents
Initialization Phase (init method) :
1. Initialization Phase (init method) :
- The servlet is instantiated and initialized by the servlet container. This phase is only executed once, when the servlet is first loaded.
- The init method is called by the servlet container to initialize the servlet. It's where you would put any startup configuration or resource allocation that the servlet needs to handle requests.
- Syntax:
java
public void init(ServletConfig config) throws ServletException {
// Initialization code here
}
Service Phase (service method) :
2. Service Phase (service method) :
- After the initialization, the servlet is ready to handle requests. This phase continues for the life of the servlet, handling each client request.
- The service method is called for each request the servlet receives. This method determines the type of request (GET, POST, etc.) and calls the appropriate method (doGet, doPost, etc.).
- Syntax:
java
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
// Request handling code here
}
Destruction Phase (destroy method)
When the servlet is no longer needed, the servlet container calls the destroy method to clean up resources before the servlet is removed from service.
This method is called once, at the end of the servlet’s life cycle, and is used to release resources like file handles or database connections.
Destruction Phase (destroy method) :
- Syntax:
java
public void destroy() {
// Cleanup code here
}
Example for Better Understanding
Here’s a simple example of a servlet that illustrates these phases:
java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ExampleServlet extends HttpServlet {
// Initialization phase
public void init() throws ServletException {
// Initialization code, like loading config or initializing resources
System.out.println("Servlet is being initialized");
}
// Service phase
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>Hello, World!</h1>");
out.println("</body></html>");
}
// Destruction phase
public void destroy() {
// Cleanup code, like closing resources or saving state
System.out.println("Servlet is being destroyed");
}