Skip to main content

Servlet Containers Explained

Servlet Containers Explained

A servlet container is a compiled, executable program responsible for loading, initializing, and executing servlets. It serves as the official Reference Implementation for Java Servlet and JavaServer Pages technologies. Developed by Sun under the Java Community Process, servlets provide a powerful, platform-independent method for server-side programming, overcoming the limitations of CGI programs.

The container handles a large number of requests and can hold many active servlets, listeners, and other components. Notably, the container and its objects are multithreaded, meaning each object must be thread-safe as multiple requests may be handled simultaneously.

Note: A servlet container can operate standalone, without a web server, or on a different host.

Types of Servlet Containers

Servlet containers can be categorized into two main types:

I. Simple Servlet Container

A simple servlet container performs the following:

  • Wait for HTTP requests.
  • Construct ServletRequest and ServletResponse objects.
  • If the request is for a static resource, invoke the process method of the StaticResourceProcessor instance, passing the ServletRequest and ServletResponse objects.
  • If the request is for a servlet, load the servlet class and invoke its service method, passing the ServletRequest and ServletResponse objects. Note that in this container, the servlet class is loaded every time it is requested.

II. Fully Functional Servlet Container

A fully functional servlet container additionally performs the following:

  • When the servlet is called for the first time, load the servlet class and call its init method (once only).
  • For each request, construct an instance of javax.servlet.ServletRequest and javax.servlet.ServletResponse.
  • Invoke the servlet's service method, passing the ServletRequest and ServletResponse objects.
  • When the servlet class is shut down, call the servlet's destroy method and unload the servlet class.

Servlet Container Functions

In general, a servlet container performs the following for each HTTP request for a servlet:

  • The servlet container loads the servlet class and calls the init method of the servlet as soon as the servlet is called for the first time.
  • The container then creates instances of javax.servlet.ServletRequest and javax.servlet.ServletResponse for each request.
  • It passes these objects by invoking the servlet's service method.
  • Finally, it calls the destroy method and unloads the servlet class when the servlet class is to be shut down.

Comments