Unknown

How a Servlet Application works

How a Servlet Application works

Web container is responsible for managing execution of servlets and JSP pages for Java EE application.
When a request comes in for a servlet, the server hands the request to the Web Container. Web Container is responsible for instantiating the servlet or creating a new thread to handle the request. Its the job of Web Container to get the request and response to the servlet. The container creates multiple threads to process multiple requests to a single servlet.
Servlets don't have a main() method. Web Container manages the life cycle of a Servlet instance.

Quick Revision on How a Servlet works

  1. User sends request for a servlet by clicking a link that has URL to a servlet.
    how a servlet application works
  2. The container finds the servlet using deployment descriptor and creates two objects :
    1. HttpServletRequest
    2. HttpServletResponse
    Request and Response objects created while servlet execution
  3. Then the container creates or allocates a thread for that request and calls the Servlet's service()method and passes the request, response objects as arguments.
    call to service() method with request and response object
  4. The service() method, then decides which servlet method, doGet() or doPost() to call, based on HTTP Request Method(Get, Post etc) sent by the client. Suppose the client sent an HTTP GET request, so the service() will call Servlet's doGet() method.
    call to doGet() or doPost() in Servlet execution
  5. Then the Servlet uses response object to write the response back to the client.
    Sending back the response to the client after servlet execution
  6. After the service() method is completed the thread dies. And the request and response objects are ready for garbage collection.
    End of Servlet Execution