LIFECYCLE OF SERVLET

Lifecycle  of Servlet :

The container in which servlet is deployed controls the lifecycle of servlet. The life cycle of a Servlet can be defined by three methods of Servlet Interface :
a. void init(ServletConfig config);
b. void service(ServletRequest request, ServletResponce response);
c. void destroy();

When a Http request is sent from a browser to an appropriate server.The server maps this request to  a particular servlet and the container performs the following steps.

  1. If an instance of the servlet does not exist, the web container
    – Loads the servlet class.
    -Creates an instance of that servlet class.
    -Initializes the servlet instance by calling the init() method.
    This method is invoked only once when the servlet is loaded.
  2. Then, it invokes the service method, passing request and response objects. It is called everytime the HTTP request is sent to the server. The service() retrieves the data from the HTTP request and processes it and creates the response for client.
  3. If the container needs to remove the servlet, it does this by calling the destroy() method to relenquish any resources handled by the servlet.
Lifecycle of Servlet
  • init() : After the servlet instance is created, the web container creates a unique ServletConfigobject that contains any initialization parameters that are specified in the deployment descriptor.

    Its prototype is :
    public void init(ServletConfig config) throws ServletException

  • service() : The service method is called by the servlet container after the servlet’s init method to allow the servlet to respond to a request. The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client.
    Each HTTP request mapped to a given servlet, the web container will create a unique request and response object to the service() method. And each request is processed a new thread and calls service.
    The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost. doPut, doDelete. etc. methods as appropriate.

    Its prototype is :
    public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException

  • destroy(): When a web application is being shutdown. the web container call the destroy() method . destroy() method is called only once at the end of the life cycle of a servlet.
    This method clean up any resources that serviet might have initialized such as close database connections, halt background threads and so on. The servlet object is marked for garbage collection.

    Its prototype is :
    public void destroy()

Leave a Reply

Your email address will not be published. Required fields are marked *