Pages Navigation Menu

Coding is much easier than you think

Servlets – Life Cycle

In this article we will learn about lifecycle of a servlet and about servlet lifecycle methods doGet() & doPost() and their implementation.
During its lifecycle, servlet went through three main methods and all these methods are called by web container, they are as follows.
1. Call the servlets init() method.
2. Call the servlets service() method.
3. Call the servlets destroy() method.
Servlet Life cycle

init() :

init() method of a servlet is called only once in its lifecycle, when a very first request comes to servlet it makes servlet state from does not exists to initialized state and during all other requests servlet remains already initialized. The container calls the init() method before the servlet can serve any client request. This method can be overridden in our servlet classes to write some initialization code in it. Initialization means something like initializing your data source or other things that we want ready before servlet starts serving the request.
Why constructor is not used for servlet initialization ?
In java, constructors are used for initialization stuff, so in case of servlet why do we use an init() method and not a constructor?
The init() method have access to two special objects called servletContext and servletConfig and we needs to use these two many times during our application. A constructor does not have access to servletConfig and servletContext that’s why we use init() instead of constructor to initialize a servlet.
We shall learn about servletContext and servletConfig in upcoming article

service() :

The service() method is the main method to where working of servlet is defined, The web container calls the service method each time when request for the servlet is received. If servlet is not initialized, then it calls the init method as described above then calls the service method. If servlet is initialized, it calls the service method. Notice that servlet is initialized only once. This method determines which http method should be called based on client request. There are 7 http methods but doGet() and doPost() are most frequently used methods with in each service request.
If user request is a get request than doGet() method of servlet is called and if the request is a post than doPost() method is called and all the business logic goes into either a doGet() or a doPost() method of servlet.

destroy() :

This method is called by the container when the servlet is no longer required.

One Comment

  1. Great description about servlet life cycle.

Leave a Comment

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