Search code examples
javaservletslifecycle

Life cycle of Servlet and its methods


I know that Servlets consist of the init, service and destroy methods. I also know that there are the doPost and doGet methods available. The question is how the service method relates to the doPost and doGet methods. Are they called from within the service method after the request is being identified? Is the service omitted when the do methods are implemented? I need some clarifications here.

For example in a life cycle of a Servlet that receives a single POST request, I would have guessed that the order would be:

  • init() is executed
  • when init() is finished the service() is called
  • service() identifies the request and calls the doPost() method
  • when both doPost() and service() finish the destroy() method is executed

Would that be right?


Solution

  • No, it isn't right.

    init() and destroy() are called only once. The servlet is instantiated by the container, and its init() method is called. That usually happens at startup, or when the first request for the servlet comes in.

    Then all the requests are handled by the service() method, which calls the appropriate doXxx() method based on the request type (as documented).

    Then, when the application is undeployed (or the server stopped), the destroy() method is called.

    The javadoc is your friend. Read it. It contains all the answers to your questions. The specifications are also freely available.