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
- User sends request for a servlet by clicking a link that has URL to a servlet.
- The container finds the servlet using deployment descriptor and creates two objects :
- HttpServletRequest
- HttpServletResponse
- 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.
- 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.
- Then the Servlet uses response object to write the response back to the client.
- After the
service()
method is completed the thread dies. And the request and response objects are ready for garbage collection.