Life Cycle of a Servlet (Servlet Life Cycle)

742 views
optmiize_your_resume_1

Servlet life cycle can be described as a series of steps through which a servlet goes during its life span, starting from loading till it gets destroyed.Let’s have look on these steps :

  1. Servlet class is loaded.
  2. Servlet instance is created.
  3. init method is Called.
  4. service method is Called.
  5. destroy method is Called.
Life Cycle of servlet
Life Cycle of servlet in java
  1. Loading Servlet Class : A Servlet class is loaded when first request for the servlet is received by the Web Container.
  1. Servlet instance creation :After the Servlet class is loaded, Web Container creates the instance of it. Servlet instance is created only once in the life cycle.
public void init(ServletConfig config) throws ServletException  
Code language: Java (java)
  1. Call to the init() method : init() method is called by the Web Container on servlet instance to initialize the servlet.

Syntax of init() method :

public void init(ServletConfig config) throws ServletException
Code language: Java (java)
  1. Call to the service() method : The containers call the service() method each time the request for servlet is received. The service() method will then call the doGet() or doPost() methos based ont eh type of the HTTP request, as explained in previous lessons.

Syntax of service() method :

public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException
Code language: Java (java)
  1. Call to destroy() method: The web container calls the destroy() method before removing the servlet instance from the service. It gives the servlet an opportunity to clean up any resource for example memory, thread etc. 

Syntax of destroy() method :

public void destroy()  
Code language: Java (java)
20%off for Ink 280 281

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More