Life Cycle of a Servlet (Servlet Life Cycle)

Servlet life cycle describes how and when a servlet object is created and initialzed, how it processes requests and how and when it is destroyed by the server. Servlet life cycle is defined by javax.servlet.Servlet interface.

We know that, javax.servlet.Servlet is the super interface, having the methods.

  • init(ServletConfig config)
  • service(ServletRequest req,ServletResponse res)throws ServletException,IOException
  • destroy()

Life cycle methods of Servlet interface:


init(): This method is invoked by the web server only once, just after the servlet object is created. It is used by the server to provide the reference of a ServletConfig object to the servlet and it can be used by the servlet programmer to define the initialization logic for the servlet.

Syntax:

public void init() throws ServletException;

ServletConfig is an interface of servlet API, implemenation of it, is provided by server vendors. An object of the class which implements this interface is provided by the server to the servlet as parameter of init() method. Role of this object will be discussed later.

service(): This method is invoked by the web server each time a request is received for the servlet. It is used by the server to get the request processed hence servlet programmers define request processing logic in it.

Syntax:

public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException;

ServletRequest & ServletResponse are interfaces of servlet API. Their implemenation is provided by server vendors. Objects of classes which implement these interface are provided as parameter of service() method by the server. These objects facilitate transfer of request data and processing result between the server and the servlet.

destroy(): This method is invoked by the web server only onece, just before the servlet is unloaded. It is used by the server to give a chance to the servlet to free the resources used by it hence it should be used by servlet programmers to define clean up operations.

Syntax:

public void destroy();

In addition to these life-cycle methods, Servlet interface provides following methods as well.

getServletConfig(): This method is used by the servlet programmers to obtain the reference of the ServletConfig object which was provided to the servlet at the time of initialization by the server. When information contained in ServletConfig object will be required, its reference need to be obtained from the servlet using this method.

Syntax:

public ServletConfig getServletConfig();

getServletInfo(): This method is used by the server and Tools such as IDE to display the servlet information such as author, version no and copyright etc hence it should be used by servlet programmers to provide such information. This method must not return any markup such as HTML or XML rather it should return plain text as a String.

Syntax:

public String getServletInfo();

Now we see how can create program

Loading the application and its Instantiation,Initialization

In the first request, the container will creates the object of the servelt and executes the init() method first, remember this init() method will be executed only once

At the time of giving the first request.

If we use 'load-on-startup tag in the web.xml then, our servelt will be loaded and init() method will be executed at the time of server starts, will see about this 'load-on-startup' in the upcoming articles In general, database connection opening or any one time object creation tasks will be written in this method, as init() will be executed only once

Executing the business logic

business logic, which is in service(-,-) method, when ever we send the request to the servlet, every time this service() method will be executed. If you send 1000 requests to the servlet, 1000 times service(-,-) method will be executed but init() method ? only one time. This service() method internally calls doGet(-,-) or doPost(-,-) methods in HttpServlet

Finally destroying

This destroy() method will be called before servlet is removed from the container, and finally it will be garbage collected as usual.

ServletLifeCycle.java


import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletLifeCycle extends HttpServlet
{
    public ServletLifeCycle()
    {    
        System.out.println("Am from default constructor");
    }
    public void init(ServletConfig config)
    {
        System.out.println("Am from Init method...!");
    }
    public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
    {    
        res.setContentType("text/html");
        PrintWriter pw = res.getWriter();
        pw.println("I am from doGet method");
        pw.close();
    }    
    public void destroy()
    {
        System.out.println("Am from Destroy methods");
    }
}

<web-app>
      <servlet>
     <servlet-name>second</servlet-name> <servlet-class>javatportal.ServletLifeCycle</servlet-class>
    <load-on-startup>1</load-on-startup>
      </servlet>
     <servlet-mapping>
     <servlet-name>second</servlet-name>
     <url-pattern>/lifecycle</url-pattern>
      </servlet-mapping>
</web-app>
	 

Flow of execute program

  1. When ever you hit the final URL (http://localhost:8080/ServletLifeCycleExample/ServletLifeCycleExample), servlet container will first loads web.xml and check the value in tag .we have given the pattern name as /lifecycle1 ]
  2. Immediately it will check the value in tag
  3. Now it will search for the same value second in under tag
  4. So value of under & are same
  5. If so container will load java class given in tag our class name is javatportal.ServletLifeCycle
  6. Finally servlet container came to 'ServletLifeCycle' class, it will executes init() method first (only once) > then service() or doGet() or doPost() method [ in our case doGet() ]
  7. Finally destroy() method will be executed before our