Servlet Life Cycle

Khushbu Kumari
5 min readDec 18, 2020

--

Servlet life cycle can be defined as a series of steps through which a servlet goes during its life span, starting from loading till it gets destroyed.

Before discussing the life cycle of the servlet, understanding of following terms is necessary.

Web Server: It is also called as HTTP Server, it can handle HTTP Requests sent by client and responds the request with an HTTP Response.

Web Container: It is also called as Servlet Container and Servlet Engine. It is a part of Web Server which interacts with Servlets. This is the main component of Web Server since it manages the life cycle of Servlet instances.

Architecture Diagram:

The above diagram describes a typical servlet life-cycle scenario.

• First the HTTP requests come to the server, which are then delegated to the servlet container.

• The servlet container loads the servlet, after which service() method is invoked.

• After that, the servlet container uses multiple thread spawning to handle multiple requests by multiple thread. Each thread then executes the service() method of a single instance of the servlet.

Stages of Servlet life cycle:

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

1) Loading a Servlet

2) Initializing the Servlet

3) Request handling

4) Destroying the Servlet

Let’s see each stage elaborately.

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

}

//rest of 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 the stack maintainance 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

}

// rest of 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:

References:

1)tutorialspoint.com

2)studytonight.com

3)geeksforgeeks.com

4)beginnersbook.com

5)jenkov.com

--

--