Wednesday, December 31, 2014

Servlet Life cycle in Java HTTPServlet

We generally start writing Java code with main() method. Servlets don't contain this method. Beginners are confused how this servlet runs. Before we start coding servlets, we need to know how it operates. What stages does it pass through. With this information, we can understand the inner working of servlets.
  • Servlets run inside servlet container, so creation and destruction of servlet is the responsibility of servlet container.
  • Servlet life cycle is defined by javax.servlet.Servlet interface, which defines how it is initialized, how it handles request and response, and how it is taken out of service
  • init() and destroy() methods are used by servlet container to do the task
  • life cycle can be understood by following flow
    • Servlet class
    • Instantiating and loading: servlet engine can instantiate more than one servlet instance
    • Initialization: (servlet config) init() method
    • Ready service method: A service method executes for each servlet interface
    • Destruction: destroy() method
    • Garbage collection: Server no longer has reference to the object

In servlet Life Cycle, the major stages are

  • Servlet Initialization: Servlet initialization is done by calling servlet’s constructor and init() method only once during servlet life cycle. Initialization is done automatically when needed or at startup if container is specifically told to load at startup. It is started automatically as soon as request is made e.g. opening database connection. It is loaded at startup if load-at-startup tag is set to nonzero.
  • Servlet Execution: No new instance of servlet is created at this stage. However, request and response objects are created, which are used to communicate with the one that is requesting. Servlet container forwards all the requests to servlet’s service() method. This service() method is executed every time request is made. The HttpServlet class breaks this service() method to more useful doGet(), doPost(), doPut(), doDelete(), doTrace(), doOptions() etc methods according to HTTP request. Only the required methods need to be overridden to carry out our task.
  • Servlet Destruction: When application is stopped or servlet container shuts down, the servlet is destroyed by calling destroy() method. This method frees the resources used by servlet.
  • Here, init() and destroy() methods are called only once during life cycle while service() method is called as many time as required after initialization.

Servlet showing life cycle in Hello World example

include java.io.*
include javax.servlet.*
include javax.servlet.http.*

public class HelloWorld extends HttpServlet {

    public String name = "Hello World"
    @Override
    public void init() throws ServletException{
        System.out.println("Method init() called");
    }
 
    //@Override is needed to inform compiler that method is overridden
    @Override
    public void destroy() {
        System.out.println("Method destroy() called");
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException,IOException {
        response.setContetnType("text/html");
        PrintWriter out=getWriter();
        out.println("<html><head><title>");
        out.println(name);
        out.println("</title></head>");
        out.println("<body><h1>Hello World</h1>You are welcome!</body></html>");    
    }
 
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
         doGet(request, response)
    }
}

No comments:

Post a Comment