JSP : Life Cycle of a Servlet

The javax.servlet.Servlet interface defines the methods that all servlets must implement and among others, three methods that are known as life-cycle methods:

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

These life-cycle methods are each called at separate times during the lifespan of a servlet, from the initial creation to the moment it's removed from service and destroyed. These methods are called in the following order:

1. When the servlet is constructed, it is initialized with the init() method.
2. Any requests from clients are handled initially by the service() method before delegating to the doXxx() methods in the case of an HttpServlet. This method is responsible for processing the request and returning the response.
3. When the servlet needs to be removed from service, it's destroyed with the destroy() method, then garbage collected and finalized. When the container decides to take a servlet out of service it first ensures that any service() method calls have completed.

No comments:

Post a Comment