Friday, October 16, 2009

Servlet Life Cycle

A Servlet is controlled by the Container. The servlet has only one state - Initialized.

  1. The web container first loads the Servlet (.class file).

  2. The web container creates an instance of the Servlet by calling the constructor

  3. The web container then calls the init() method of the servlet which initializes the servlet. It is called only once

  4. The web container then calls the service() method of the servlet which in turn calls the respective doGet() or doPost() depending on the type of request. For each request, a separate thread is used.

  5. Finally the container calls the destroy() method which cleans up and make it ready for garbage collection. It is also called only once.



Servlet classes and life cycle methods:

javax.servlet.GenericServlet implements javax.servlet.Servlet (interface)
javax.servelt.http.HttpServlet extends javax.servlet.GenericServlet
MyServlet extends javax.servelt.http.HttpServlet


The init() method of the Generic Servlet is called if it is not overriden in the MyServlet. The init() can be used to initalize the database before processing the request.
The service() method of the HttpServlet is called. We don't need to override it.
The service() method in HttpServlet calls the overrriden doGet() or doPost() of MyServlet.


Note:


  • There is only one servlet instance per JVM

  • Each request runs in a separate thread.

  • Servlet is loaded and initialized only once when the container starts up.

  • init() always completes before the first call to service()

  • The constructor of the servlet class just creats an ordinary object. It becomes a servlet when it is initalized after init().

Followers