Christmas SPECIAL OFFER... IT SECURITY & ETHICAL HACKING FROM BASIC TO ADVANCE . Batch Starts From 1st January 2021 . BIG DISCOUNT ON COURSE FEE UPTO 50% !!! Hurry Up! 1st cum 1st basis.

What is Servlets? Explain about life cycle of a servlet.

Debashis Maharana, Aug 10/2019

Servlets is a Java based web technology from Sun Microsystems. It is a Java EE technology. It is an API.

On the other hand, a servlet is a web server side piece of code that enhances the functionality of the web server. A servlet is a dynamic web resource.

A servlet is a servlet container managed public Java class that implements javax.servlet.Servlet interface. Servlet interface is a web component contract between the web component and the web container.

The following code gives the general structure of a servlet:-

The init(), service() and destroy() are abstract methods of Servlet interface. Whenever something happens in the life of the servlet, Servlet engine calls these methods implicitly (automatically) and hence these are known as Life Cycle methods.

A user defined servlet class has 4 life cycle phases:-

  1. Instantiation phase
  2. Initialization phase
  3. Servicing phase
  4. Destruction phase

Instantiation phase:-

Servlet engine loads user defined servlet class from secondary memory into primary memory dynamically. Servlet engine creates the instance of loaded servlet class with methods of Reflection API.

Initialization phase:-

During instantiation phase, a servlet is missing with 2 pieces of information:

  1. Context information
  2. Initial configuration information

When the above informations are not available even though servlet object is ready, it doesn’t possess complete servletness. Servlet engine creates ServletConfig interface object and encapsulates the above missing informations in it. Now Servlet engine calls init(ServletConfig) by supplying ServletConfig object as argument. One’s init() is completely executed, initialization phase of the servlet is over and the servlet is ready to serve the client’s request.

The instantiation and initialization happens only one’s in the lifetime of a servlet.

Servicing phase:-

Servlet engine creates ServletRequest interface object encapsulating the user input. Servlet engine creates ServletResponse interface object encapsulating client socket details. Servlet engine calls service method by supplying request and response object references as arguments.

Servlet engine calls service method of servlet for each client request.

Destruction phase:-

When the web application is unloaded (undeployed), Servlet engine calls destroy()of the servlet and marks the servlet instance for garbage collection.

Leave your Comment:-