The life cycle of a servlet

A servlet's life cycle has three phases. These are depicted in the following diagram:

                

Let's look at each phase of the servlet life cycle:

  • Initialization: The first phase in the Servlet's life cycle is initialization. In this phase, the resources that a servlet needs to serve the request are created and initialized. The Servlet classes implement the contract of the javax.servlet.Servlet interface, and the javax.servlet.Servlet interface declares the init() method that represents the initialization. When the servlet is loaded by the container, it invokes the init() method to create and initialize the resources. This init() method is invoked only once during the servlet's life cycle after the servlet has been loaded into the container.
  • Service: The service phase in the servlet's life cycle represents the interaction between the servlet and the client. Whenever the server receives a request from the client for a servlet, it creates a new servlet and invokes the service() method. The Servlet interface declares the service() method, which takes the request (ServletRequest) and response (ServletResponse) objects. The ServletRequest object represents a client's request for a dynamic resource, and the ServletResponse object represents the servlet's response to the client. The service() method implementation checks for the HTTP request type, which could be something such as GET, POST, PUT, or DELETE, and invokes an appropriate method, such as doGet(), doPost(), doPut(), or doDelete().
  • Destruction: Destruction is the last phase in the servlet's life cycle. In the servlet's destruction phase, it gets removed from the container that it was loaded by during its initialization phase. The Servlet interface declares the destroy() method and the container invokes this method just before the servlet gets removed from the container. This allows the servlet to clean up resources and gracefully terminate them.

To summarize, once a servlet has been loaded into the container, it creates and initializes resources in its initialization phase. In its service phase, it serves a request from the client; in its destruction phase, however the resources gets cleaned up and the servlet get removed from the container.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset