Step4: Servlet life cycle

serLife

Important –

1- Web container – It is a part of web server, which is responsible for managing the lifecycle of servlets, managing the initialization and finalization of servlet and also for handling the request and response for the servlet.

StageDescriptionExample
LoadingThe Servlet class is loaded into memory by the classloader.Servlet class is loaded by web container’s classloader during startup or when first request comes for the servlet
InstantiationAn instance of the Servlet class is created.A new instance of servlet class is created by web container when first request comes for the servlet
init()The init() method is called by the container to initialize the Servlet.

This method is only called once during the life cycle of a Servlet.
init method can be used to perform one-time setup, like creating database connections, loading configuration files.
service()The service() method is called by the container to process client requests. The service() method then calls the doGet() or doPost() method depending on the type of request.service method invokes doGet/doPost method based on the request type
destroy()The destroy() method is called by the container to end the Servlet life cycle. This method gives the Servlet an opportunity to clean up any resources that it has allocated.destroy method can be used to release resources like database connections, close open files, stop background threads

Now with this example, you can see how the different stages of the Servlet life cycle are implemented:

public class MyServlet extends HttpServlet {
   
    public void init() throws ServletException {
        // one-time setup, like creating database connections, loading configuration files
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // process GET request
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // process POST request
    }
    public void destroy() {
        // release resources like database connections, close open files, stop background threads
    }
}