Servlet life cycle

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

Servlet Life cycle :

Hello all, this article will help understand how a servlet works and what are the servlet life cycle phases. To understand, we are simply going to create a HelloServlet that overrides servlet lifecycle methods. There are three servlet life cycle methods.

  • Init method
  • service method
  • destroy method

Init() method :

  • public void init() throws ServletException . Its the method signature.
  • Called only once in servlet life cycle after it is instantiated using the default no-argument constructor.
  • Servlet gets its servletness only after  init()  method completes execution. Servlet is able to handle client requests and serve the response after it.
  • When servlet is ready to handle requests, the job of  init()  is done. It is never called again.

service() method:

  • All client requests are served by service() method.
  • This method called again and again depending on client requests withing servlet life cycle
  • Depending upon the type of request, e.g. GET, POST, corresponding doGet or doPost method is called from HttpServlet .

destroy() method

Destroy method is only called once in servlet life cycle. That is when servlet is about to get destroyed.

The program will help understand these methods.

Configure this in web.xml

Deploy the application in tomcat server. Start it and hit http://localhost:8080/<YourAppName>/HelloServlet . Hit it multiple times so that servlet is requested again and again.

You will see the output something like

This confirms that  init()  method is called only once while  doGet  method is called multiple times through service() method. The diagram elaborates it more.

Servlet life cycle

  1. HelloServlet.class  is loaded into the web application when container starts.
  2. After that, HelloServlet is instantiated using its no-argument constructor. Right now it is just plain old java object. It cannot handle requests made by client.
  3. After instantiation, init()  method runs and here it gets it servletness. It has found its purpose in servlet life cycle.
  4. Now that the purpose of servlets very existence is known, it handles all the requests made to it. Every time a request is made,  service()  method runs in a separate thread.
  5. destroy()  method runs when servlet is about to get destroyed.

Hope this helped.


Share Button

1 comment for “Servlet life cycle

  1. TG
    October 14, 2015 at 12:14 pm

    Straight to the point. A clean refresher, thx!

Leave a Reply

Your email address will not be published. Required fields are marked *