Servlet – its life cycle and characteristics

What is Servlet ?

  • Servlets are simple Java programs that run on the servers.
  • Servlets are most commonly uses with HTTP. So, servlets are also known as HTTP servlet.
  • Servlet can process and store the data submitted by an HTML form.
  • Servlets are useful for providing dynamic content. The life cycle of Servlet
    Servlet have various characteristics and life cycle. Here, we will study about Servlet – its life cycle and characteristics.

Life cycle of Servlet

life cycle of servlet

Stages of the Servlet life cycle:

1. Loading a Servlet

  1. The first stage of the Servlet lifecycle involves loading and initializing the Servlet by the Servlet container.
  2. The Servlet container performs two operations in this stage:
    i. Loading: Loads the Servlet class.
    ii. Instantiation: Creates an instance of the Servlet. To create a new instance of the Servlet, the container uses the no-argument constructor.

2. Initializing a Servlet

  1. After the Servlet is instantiated successfully, the Servlet container initializes the instantiated Servlet object.
  2. The container initializes the Servlet object by invoking the Servlet. init(ServletConfig) method which accepts ServietConfig object reference as a parameter.

3. Handling request

  1. After initialization, the Servlet instance is ready to serve the client requests.
  2. The Servlet container performs the following operations when the Servlet instance is located to service a request.
    i. It creates the ServietRequest and ServietResponse objects.
    ii. After creating the request and response objects it invokes the Serviet.service(ServietRequest, ServietResponse) method by passing the request and response objects.

4. Destroying a Servlet

  1. When a Servlet container decides to destroy the Servlet, it performs the following operations,
    i. It allows all the threads currently running in the service method of the Servlet instance to complete their jobs and get releases.
    ii. After currently running threads have completed their jobs, the Servlet container calls the destroy() method on the Servlet instance.
  2. After the destroy() method is executed, the Servlet container releases all the references of this Serviet instance so that it becomes eligible for garbage collection.

Characteristics of a servlet

  1. Serviet operates on input data that is encapsulated in a request object.
  2. Serviet responds to a query with data encapsulated in a response object.
  3. Servlet can call EJB components to perform business logic functions.
  4. Servlet can call JSPs to perform page layout functions.
  5. Serviet can call other servlets.

Read more about types of software