Monday, July 25, 2016

Life Cycle of a Servlet

Life Cycle of a Servlet

The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the servlet
  1. Servlet class is loaded.
  2. Servlet instance is created.
  3. init method is invoked.
  4. service method is invoked.
  5. destroy method is invoked.      




Servlet Class is Loaded:

The classloader is responsible to load the servlet class. The servlet class is loaded when the first request for the servlet is received by the web container.

Servlet instance is created

The web container creates the instance of a servlet after loading the servlet class. The servlet instance is created only once in the servlet life cycle.

init method is invoked

The web container calls the init method only once after creating the servlet instance. The init method is used to initialize the servlet. It is the life cycle method of the javax.servlet.Servlet interface. Syntax of the init method is given below:
public void init (ServletConfig config) throws ServletException  

service method is invoked:

The web container calls the service method each time when request for the servlet is received. If servlet is not initialized, it follows the first three steps as described above then calls the service method. If servlet is initialized, it calls the service method. Notice that servlet is initialized only once. The syntax of the service method of the Servlet interface is given below:
public void service(ServletRequest request, ServletResponse response)   
                   throws ServletException, IOException  

destroy method is invoked

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. The syntax of the destroy method of the Servlet interface is given below:
public void destroy()  


Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home