Servlet Life Cycle

Servlet is an instance of a class which implements the javax.servlet.Servlet interface. Most servlet, however, extend either GenericServlet or HttpServlet classes.

Generic Servlet is used for protocol independent and HttpServlet for Http Requests.

Life Cycle Methods:

1) init(): Servlet is initialized by calling this method and it is called once in complete life cycle. It gets called when servlet gets loaded in memory.

public void init() throws ServletException {
   // Initialization code...
}

2) Service(): This method is called to process client request. It is called by container and invokes doGet,doPost,doPut(Part of HttpServlet class) etc as depending upon request type.

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

}

When ever new request comes this methods gets called every time to service the request as a seperate thread. Depending upon method specified in form tag on jsp page, corresponding method will get invoked from servie method.

3) destroy(): It is called when servlet is terminated or server deletes its instance. It is also called once in complete life cycle.

public void destroy() {
   // Finalization code...
}

These methods are implemented in GenericServlet class.

Example:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet {
 
  private String name;

  public void init() throws ServletException
  {
       //initialization
      name = "Hello World";
  }

  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
      // Set response content type
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      out.println("Name:" + name + "");
  }
  
  public void destroy()
  {
      // do nothing.
  }
}