In the servlet life cycle, first the servlet is instantiated (the default constructor runs) and then the init() runs.
init() gives us a chance to initialize our servlet before handling any client requests.
Is it possible that we can write the default constructor, do the initialize the servlet (job of init()) inside the constructor?
In that case we will not need the init().
So the questions is what is the use of init() if I can do the initialization in the default constructor?
Never, ever, use a constructor in a servlet. It's up to the servlet container to construct and destroy servlet instances at its discretion. That's why there is an init method - to allow the developer to execute code before the servlet is put into service.
As an explanation of why it is this way, it is allowable for the container to serialize the servlet object at shutdown, and reinstate if from storage at the next startup. Thus the constructor wouldn't be run again. The init method will be called, however, after the object is deserialized.
Joined: Dec 23, 2008
Hi Ulf, Nishan and Steve,
Thanks for clearing my doubt.
after the constructor runs, a normal java object is created.
but only after the init method runs, the java object gets a servlet config from the container, thus transforming it from a normal java object to a servlet object.
It also makes sense that container creates and destroys the instances of servlet. so it is not wise to write the default constructor.
Thanks Steve for the insight about the servlet object serialization.