Sobes.tech
Middle

How does the servlet container manage the servlet's lifecycle? What methods are called and when?

sobes.tech AI

Answer from AI

The container manages the servlet's lifecycle through a set of methods: init, service, destroy.

  1. Loading the servlet class: When the container receives the first request to the servlet or at application startup (if configured).

  2. Creating a servlet instance: The container creates a single instance of the servlet class for the entire application.

  3. Calling init(): The container calls the init(ServletConfig config) method once after creating the instance. In this method, initialization can be performed, resources loaded, and servlet configuration obtained. The method should not be called again until the servlet is destroyed and recreated.

    // java
    public void init(ServletConfig config) throws ServletException {
        // Servlet initialization
        this.config = config;
        // Getting initialization parameters
        String param = config.getInitParameter("someParam");
    }
    
  4. Calling service(): For each incoming request, the container calls the service(ServletRequest request, ServletResponse response) method. This method processes the request and generates a response. It usually delegates processing to specific HTTP methods (doGet, doPost, etc.) in subclasses of HttpServlet. The service method is multithreaded; the container may invoke it concurrently for multiple requests.

    // java
    public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
        // Check request type and delegate to appropriate method
        if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
            // Delegate to HttpServlet
            super.service(request, response);
        } else {
            // Handle other request types
            throw new ServletException("Only HTTP requests are supported");
        }
    }
    
    // Example doXXX method in HttpServlet
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Handle GET request
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<h1>Hello</h1>");
    }
    
  5. Calling destroy(): The container calls the destroy() method once before destroying the servlet instance. This occurs when stopping the application or removing the servlet from the container. Resources are released in this method (e.g., closing database connections or files). After calling destroy, the container may perform garbage collection on the servlet instance.

    // java
    public void destroy() {
        // Release resources
        // For example, close connections
    }
    

The lifecycle can be summarized in a table:

Method Called Purpose
init() Once after creating the servlet instance Initialization, resource loading
service() For each incoming request Request processing, response generation
destroy() Once before destroying the servlet instance Resource release, shutdown

The container guarantees that init will be called before service, and destroy will be called after the last service call. service methods may be invoked concurrently.

How does the servlet container manage the servlet's… - sobes.tech