Life Cycle of Servlet

tutorial and example
tutorial and example

Servlet container is responsible to manage the lifecycle of a servlet. Servlet provides three methods as a part of its lifecycle. Let’s study the lifecycle of servlets with the following steps.

  • Loading class: This is an initial stage of servlet in which a servlet class is loaded whenever a request is made.
  • Creating instance: As soon as the class is loaded, servlet container created the instance of that class.
  • init(): In this step, the servlet container invokes an init() method to initialize the servlet instance. An object of ServletConfig interface is passed within this method. Note that init() method is invoked once in a lifetime of a servlet.
  • service(): After  initialization, servlet container invokes service() method for every request. Each request is handled by a separate thread. This method is used to perform various operations.
  • destroy(): This is the final stage of the servlet. In this phase, servlet container invokes destroy() method for closing the servlet. As soon as destroy() method is invoked the memory allocated to servlet and its object is collected by the automatic garbage collector. Note that destroy() method is invoked once in a lifetime of a servlet.