Servlet Life Cycle

    The life cycle contains the following steps:
  • Load Servlet Class.
  • Create Instance of Servlet.
  • Call the servlets init() method.
  • Call the servlets service() method.
  • Call the servlets destroy() method.
Servlet Container

    1. init() method:-
  • The servlet is initialized by calling the init () method.
  • The init method is called only one time,when servlet is first created,never call again for each user request.
  • The init() method simply create or load some data that will be used overall life of the servlet.

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


    2. service()method:-
  • The servlet container calls the service() method to handle requests coming from the client or browsers and to write the formatted response back to the client.

  • The service() method checks the HTTP request type such as GET ,POST etc and calls doGet, doPost etc.

  • public void service (ServletRequest request,
    ServletResponse response) throws ServletException, IOException
    {
    }
      doGet() Method:-
    • GET is HTTP method. it works to tell server to get a resource and send it server.
    • it should be handled by doGet() method.

    • public void doGet (HttpServletRequest request, HttpServletResponse response)
      throws
      ServletException, IOException
      {
      // Servlet code
      }
      The doPost() Method:-
    • POST ,you can request something and at same time send form data to server.
    • it should be handled by doPost() method.


    • public void doPost (HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException
      {
      // Servlet code

      }

        3. destroy() method :-
      • The destroy() method is called only one time at the end of the life cycle of a servlet.
      • It gives opportunity to clean up any resource such as Memory,thread etc.

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