Whenever a client sends a request to the J2EE application server for a particular servlet, the J2EE Application server passes the request to the Web container. The Web container checks whether an instance of the requested servlet exists. If the servlet instance exists then the Web container delegates the request to the servlet, which process the client request and sends back the response.
In case the servlet instance does not exist, the Web container locates and loads the servlet class. The Web container then creates an instance of the servlet and initializes it. The servlet instance starts processing the request after initialization. The Web container passes the response generated by the servlet to the client. The following figure shows the interaction between J2EE Application server and Web container.
The Web container manages a servlet by invoking various life cycle methods. These methods are defined in the Servlet API. It is a collection of classes and interfaces that we can use to develop a servlet. These classes and interfaces are packaged in the javax.servlet and javax.servlet.http packages.
What is Servlet Container?
Servlet resides in Container which is known as Servlet Container. Servlet container provides the execution environment for Servlet.
E.g. Tomcat Servlet container is generally used to service client request for dynamic contents.
Main functions of Servlet container:
- Network Service: The servlet container along with web server or application server provides the required network services for communicating the request and response between the client and the server.
- Coding / Decoding: The servlet container decodes MIME (Multipurpose Internet Mail Extensions) based request and then pass this request object to the servlet for further execution and similarly formats the response object into MIME response so that web browser can understand the servlet generated output.
- Lifecycle Management of Servlet is also taken care by Servlet container.