The interface javax.servlet.Servlet defines the following three methods known as servlet life cycle methods.
public void init(ServletConfig config) throws ServletException
public void service(ServletRequest req, ServletResponse res) throws ServletException, java.io.IOException
public void destroy()
The container first creates the servlet instance and then executes the init() method.
init() can be called only once in its life cycle by the following ways:
a) Through the ‘load-on-startup’ tag using the web.xml. This makes the servlet to be loaded and initialized when the server starts.
b) For the first time only in its life cycle, just before the service() is invoked.
c) Server administrator can request for the initialization of a servlet directly.
Whenever a client requests for the servlet, everytime the service() method is invoked during its life cycle. From service() then it is branched to the doGet() or doXx..() methods for a HttpServlet. The service() method should contain the code that serves the Servlet purpose.
destroy() method is invoked first, then Servlet is removed from the container and then eventually garbage collected. destroy() method generally contains code to free any resources like jdbc connection that will not be garbage collected.
This Servlet tutorial was added on 05/05/2008.