Life Cycle Of a Servlet

Pushkar Baichwal
5 min readMay 19, 2021

What is a Servlet?
Servlets are nothing but small JAVA Programs that execute on the server side of the Web Connection. As we know in JAVA, Applets dynamically extend the functionality of the Web Browser, similarly Servlets dynamically extend the functionality of the Web Server. They generate dynamic content and interact with the Web Clients using Request - Response Model.

Now, before discussing the whole life cycle of the Servlet, let’s understand the following necessary terms.

Web Server : Also known as HTTP Server. It handles HTTP requests from client and responds to the corresponding requests with HTTP responses.

Web Container : Also known as Servlet Container or Servlet Engine. It’s a part of web server that interacts with servlets.

The above figure is a typical pictorial representation of a servlet’s life cycle.

  1. First all the requests are heading towards the server and then directed to the servlet container.
  2. Then, the servlet is loaded by the Servlet Container.
  3. Later, servlet container handles the multiple requests by multiple threads.

Life Cycle Of A Servlet

The three main methods central to the life of a servlet are :
- init()
- service()
- destroy()

The Servlet container uses the javax.servlet.Servlet interface to understand the Servlet object and manage its entire life cycle.This whole process mainly consists of four stages.

1) Loading a Servlet

2) Initializing the Servlet

3) Request handling

4) Destroying the Servlet

1)Loading a Servlet:
The Web container or Servlet Container loads the Servlet at either of the following two stages:

i) Initializing the context, on configuration of the Servlet with a 0 or positive integer value.
ii) If the Servlet is not preceding stage, it may delay the loading process until the Web container determines that this Servlet is needed to service a request. The Servlet container performs two operations at this stage:

a) Loading : Loads the Servlet class.
b) Instantiation : Creates an instance the Servlet by using the no-argument constructor.

2) Initializing a Servlet:
After successful instantiation, Servlet container will initialize servlet instance by invoking the Servlet.init(ServletConfig) method which accepts ServletConfig instance reference as parameter.
The Servlet container calls the Servlet.init(ServletConfig) method at once only, immediately after that the Servlet.init(ServletConfig) instance is instantiated successfully. This method is used for initializing the resources, such as JDBC datasource.
If the Servlet is failed to initialize ,then Servlet container may throw the ServletException or UnavailableException.

3)Handling request:
After successful initialization, Servlet container performs the following operations when the Servlet instance is ready to service a client request :
• It creates the ServletRequest and ServletResponse instances.If this is a HTTP request, then the Servlet container creates HttpServletRequest and HttpServletResponse instances.
• After creation of the request and response instances, it invokes the Servlet.service(ServletRequest, ServletResponse) method by passing the request and response instances.
The service() method may throw the ServletException or UnavailableException or IOException within the duration in which the request is being processed.

4) Destroying a Servlet: Servlet container performs the following operations at the time of destruction of Servlet instance.
It permits all the threads which are currently running in the service method of the Servlet instance to complete their tasks and get released.
• After all currently running threads have completed their tasks, the Servlet container calls the destroy() method on the Servlet instance.
After the execution of the destroy() method, the Servlet container releases all the references of this Servlet instance so that it becomes ready for garbage collection.

Servlet Life Cycle Methods:

The class Servlet has provided methods to control and supervise the life cycle of servlet. There are 3 life cycle methods in the Servlet interface. They are as follows:

  1. init() method:
    - This method is called by the Servlet container is to indicate that this Servlet instance is instantiated successfully and is about to put into service.
    - This method is called only once in the lifetime of the Servlet instance, hence “connected architecture” code is written inside it because we only want once to get connected with the database.
    - This method requires only one parameter, i.e ServletConfig object.
    - This method may throw the ServletException.
    - Once the Servlet instance gets initialized, it becomes ready to handle the client request.
    - Syntax :
    init() method
    public class MyServlet implements Servlet{
    public void init(ServletConfig config) throws ServletException { //initialization code
    }
    }

Points to be noted about init() method:

1)One may wonder that if init() method is supposed to be called only once then why not to use constructor.Answer to this query is that if the connection fails to establish, then we can throw an exception from init() and the rest of the steps stop executing. But in the constructor we can’t use, throw in its prototype otherwise it is an error.
2)In programs of Servlet, it is recommended to use (or override)the non-parameterized version of init() method.This is because non-parametrized version needs less method calls than parametrized version which has overhead of using super keyword .Thus,it requires less execution time,eases the stack maintenance job of CPU and thus increases speed and efficiency of execution.

2) service() method:
- The service() method provides the connection between client and server.
-The web server calls the service() method to handle requests coming from the client( web browsers) and to send responses back to the client.
-This method can determine the type of Http request (GET, POST, PUT, DELETE, etc.) .
-This method invokes various other methods such as doGet(), doPost(), doPut(), doDelete(), etc. as determined by the Http request.
-This method accepts two parameters.
ServletRequest object :- to collect the data requested by the client by encapsulating the connection between client and server.
ServletResponse object :- to generate the output content by encapsulating the connection from server back to the client.
-This method may throw ServletException and IOException .
-Syntax:
service() method
public class MyServlet implements Servlet{ public void service(ServletRequest res, ServletResponse res)throws ServletException, IOException {
// request handling code
}
}

3) destroy() method:
-Just like the init() method, destroy() method is also called only once during the entire life cycle of the Servlet instance.
- This method gets invoked at the end of the life cycle of the servlet instance.
-This method performs following tasks:

i)Closing database connection
ii)de-allocation of memory space of the Servlet instance
iii) releasing resources that are allocated to the Servlet and other cleanup activities -Invoking this method signals garbage collection.
Syntax:
destroy() method
public void destroy(){
// Finalization code…
}

SAMPLE PROGRAM:

This brings us to the end of this article. Hope you are clear with all that has been shared with you.
This article is contributed by Pushkar Baichwal, Akash Gorantyal and Aditya Sadamate.

References :
1. tutorialsoint.com
2. geeksforfeeks.com
3. studytonight.com

--

--