Servlet Life Cycle

Servlet Life Cycle
  • When the servlet is first created, its init method is invoked, so init is where you put one-time setup code. 
  • After this, each user request results in a thread that calls the service method of the previously created instance. 
  • Multiple concurrent requests normally result in multiple threads calling service simultaneously, although your servlet can implement a special interface (SingleThreadModel) that stipulates that only a single thread is permitted to run at any one time. 
  • The service method then calls doGet, doPost, or another doXxx method, depending on the type of HTTP request it received. 
  • Finally, if the server decides to unload a servlet, it first calls the servlet’s destroy method. 
init() method:
  • It is called 1 time only.
  • It is called when the servlet is first created, and not called again for each user request.
  • The init() method simply creates or loads some data that will be used throughout the life of the servlet.
  • There are two types…
  • General Initialization
  • Parameter Initialization
service()
  • It is called N times.
  • The service method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc., as appropriate. 
  • A GET request results from a normal request for a URL or from an HTML form that has no METHOD specified. 
  • A POST request results from an HTML form that specifically lists POST as the METHOD. 
  • Other HTTP requests (Put, Delete, Options…) are generated only by custom clients.
Service methods:
  • It is called N times based upon user request. 
  • There are Get, Post, Delete, Put, Options, Trace request.
  • Figure:
  • 99% times you have to take care Get and Post, only.
  • To handle request such asGet – doGet, Post – doPost, Put – doPut, Options – doOptions, Trace – doTrace methods, respectively.
Destroy():
  • The destroy() method is called by container before removing a servlet instance from service. 
  • It is called 1 time only.
  • The destory() will be called :
    • when the container shuts down or the application shuts down;
    • when the container decides that there is a shortage of memory;
    • when this servlet hasn't got a request in a long time.
Summary:
The init Method (1 Time)
  • It is used for one-time initializations
The Service Method (N Times)
  • Each time the server receives a request for a servlet, the server seed a new thread and calls service.
  • The doGet, doPost and doXXX Methods (N Times)
  • The service method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc., as appropriate.
The destroy Method (1 Time)
  • To remove previously loaded instance.

Thanks a lot for query or your valuable suggestions related to the topic.

Previous Post Next Post

Contact Form