[轉貼]The Life Cycle of a Servlet

The Life Cycle of a Servlet

This tutorial explains the Servlet interface and Servlet life cycle. A servlet example is given at the end which demonstrates the life cycle of a servlet.

Servlets are managed components. They are managed by web container. Of the various responsibilities of web container, servlet life cycle management is the most important one. A servlet is managed through a well defined life cycle that defines how it is loaded, instantiated ad initialized, handles requests from clients and how it is taken out of service. The servlet life cycle methods are defined in the javax.servlet.Servlet interface of the Servlet API that all Servlets must implement directly or indirectly by extending GenericServlet or HttpServlet abstract classes. Most of the servlet you develop will implement it by extending HttpServlet class.

The servlet life cycle methods defined in Servlet interface are init(), service() and destroy(). The life cycle starts when container instantiates the object of servlet class and calls the init() method, and ends with the container calling the destroy() method.

public void init(ServletConfig config) throws ServletException<br />
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException<br />
public void destroy()

The servlet life cycle consists of four steps, instantiation, initialization, request handling and end of service. Each of these steps is explained below.

Loading and instantiation


During this step, web container loads the servlet class and creates a new instance of the servlet. The container can create a servlet instance at container startup or it can delay it until the servlet is needed to service a request.

Initialization


During initialization stage of the Servlet life cycle, the web container initializes the servlet instance by calling the init() method. The container passes an object implementing the ServletConfig interface via the init() method. This configuration object allows the servlet to access name-value initialization parameters from the web application

Request handling A.K.A service() method


After a servlet is properly initialized, the servlet container may use it to handle client requests. Requests are represented by request objects of type ServletRequest. The servlet fills out response to requests by calling methods of a provided object of type ServletResponse. These objects are passed as parameters to the service method of the Servlet interface. In the case of an HTTP request, the objects provided by the container are of types HttpServletRequest and HttpServletResponse.

Multithreading issues

During the request processing phase, there can be multiple threads running the service() method of a servlet instance. The Servlet container can send multiple concurrent requests through the service method of the servlet. So it's upto the developer to properly handle the concurrency.



  1. If the servlet implements the SingleThreadModal interface, Servlet container guarantees that there will be only one request thread at a time in service method. The servlet container can satisfy this requirements by serializing requests to the service method or by maintaining the pool of servlet instance.
  2. If the servlet does not implement SingleThreadModal but either of service, doGet or doPost methods has been defined with the synchronized keyword, the servlet container can not create pool of servlet instance but must serialize requests.

    Because of performance reasons, using SingleThreadModal and defining doGet, doPost or service methods with synchronized keywords is highly discouraged.

    Though SingleThreadModal can protect your servlet instance variables by guaranteeing only one thread in service method at a time, It doesn't guarantee thread safety and hence SingleThreadModal is deprecated. So its always a good idea to avoid SingleThreadModal and look for alternative solutions.

    End of service destroy() method


    When servlet container determines that the servlet should be removed from the service, it calls the destroy() method of the servlet to allow servlet to release any resources it is using (eg. database connections or file handles). Before calling the destroy() method, the container allows any request threads that are currently running in the service method to complete execution within a defined time limit. Once the servlet is removed out of service, container will not send any requests to the servlet. If the servlet needs to be put in service again, the container will create a new servlet instance and the life cycle begins from the initialization phase.

    Understanding the Servlet life cycle with an example

    We will create a Servlet that will help you in better understanding the life cycle of a servlet.

    import java.io.IOException;

    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 ServletLifeCycleExample extends HttpServlet {

    private int count;

    @Override
    public void init(ServletConfig config) throws ServletException {
    super.init(config);
    getServletContext().log("init() called");
    count=0;
    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    getServletContext().log("service() called");
    count++;
    response.getWriter().write("Incrementig the count: Count = "+count);

    }

    @Override
    public void destroy() {
    getServletContext().log("destroy() called");
    }

    }

    Above ServletLifeCycleExample Servlet extends HttpServlet and overrides init() Service() and destroy() methods. The servlet logs a message into server log file when servlet is initialized and sets counter to 0. Every time the service method is called, it increments the counter by 1 and displays the current value of counter to user. finally when destroy method is called, it logs a message to server log file.

    Compile above class and put it into WEB-INF/classes directory. Define the servlet and servlet mapping into web.xml file. If you do not know how to define the servlet in web.xml see this servlet example.

    Deploy the application and start the server. Call the servlet by opening the URL that you specified as url-pattern in web.xml. See the server log file. Hit the URL multiple times and you will see that a message is logged every time the service() method is called. The current value of counter will be displayed in browser.


    轉貼至 http://www.servletworld.com/servlet-tutorials/servlet-life-cycle.html

    留言

    這個網誌中的熱門文章

    WPF - 深入 Style

    C# – M$ Chart Control 自定 ToolTip 的顯示

    Vue.js - 基礎介紹教學