Life Cycle Of A Servlet Explained Handling Servlet Life-Cycle Events Servlet Life Cycle Servlet Interview Questions Java Servlet Programming

Life Cycle Of A Servlet 

A servlet is a java code which runs at the server side to process request and return response to the client.

In other words, a servlet is an extension to the server which processes request and returns response as an HTML page to the client. Like applets we donot have main method in a servlet. As in case of applet,its life cycle is taken care by the browser itself,similarly in case of servlet its life cycle of a servlet is managed by the server/container.


Life Cycle Of A Servlet denotes the phases it goes through. These phases are symbolized by the life cycle methods in the servlet.As server manages the Life Cycle Of A Servlet, these life cycle methods are called by the server itself. Let us have a look at different Life Cycle methods Of A Servlet. These are as follows :


  1. init
  2. service
  3. destroy


1. init : The init method is the first Life Cycle method Of A Servlet. It is this method which after being called by the server makes a servlet eligible for being called a servlet. After the servlet class constructor is called,the init method is called by the server. The method looks like :

public void init(ServletConfig sc) throws ServletException {
  // Initialization code...


Here we can see that the ServletConfig object is passed to the init method. This object is created by serverand passed to the init method. Having received the ServletConfig object ,a servlet is said to be a servlet.

2. service : This life cycle method is called every time a request is sent to the servlet .This means that the servlet’s init method has been called and servlet is ready to process requests.This method looks like :

public void service(ServletRequest request,
                    ServletResponse response)
      throws ServletException, IOException{

3.destroy : This is the last phase in the Life Cycle Of A Servlet. Before the servlet object is garbage collected at the server side this method is called to relinquish the resources at the server side. This method looks like :

public void destroy() {
    // Finalization code...

It can be noted that the init method is called only once in the Life Cycle Of A Servlet, service is called as many times as many the requests are fired and destroy is called only once in the Life Cycle Of A Servlet.

Number of View :753

Tags: , , , , , , , , , ,

  1. No comments yet.

Content Protected Using Blog Protector By: PcDrome.

Mahol Dot Org is Stephen Fry proof thanks to caching by WP Super Cache