Ad

Wednesday 21 August 2013

Servlet Life Cycle - Callback Methods

When we start the app/webserver ,the webscontainer will be loaded.Then the webcontainer will
loads the servlet and it is responsible for maintaining the servlet life cycle by calling the Servlet call back methods.The three callback methods servlet provides to the webcontainer are
  1. init()
  2. Service()
  3. destroy()

1.init()
 This method will be called only once by the webcontainer during service life cycle.Init method
provides us to write any initialization code for the servlet like creating the database connection,socket connections or loading any objects etc.Init method will be called by the container either at

  •    For the servlets which are declared as <load-on-start-up> in web.xml,Init method will be called on      Server starup.Thus the Servlet will be initiatized during the server startup.
  •    For the servlets which are not declared as <load-on-startup> in web.xml,Init method will be called      on handling the first request for the servlet.Thus the servlet will be initiatizied only this time.On          handling the Subsequent request,Init method wont be invoked.


2.Service()
Once the servlet is initialized(ie init() method is invoked),servlet is ready to handle client requests.On receiving the request for the Servlet,the container will invoke the Service method.Depending on the Value of the Http Method in the  request(ie GET/POST),doGet() or doPost()
method will be invoked from the service method.

3.destroy()
When the Servlet is about to be destroyed,Container will call the destroy() call back method of the servlet.It provides us to write any clean up code like cleaning up the database connection,socket connection etc.As we expect this destroy call back  method will be invoked on shutting down the
server.

No comments:

Post a Comment