How Tomcat Works

Application 1

Now, let's examine servlet programming from a servlet container's perspective. In a nutshell, a fully-functional servlet container does the following for each HTTP request for a servlet:

  • When the servlet is called for the first time, load the servlet class and call the servlet's init method (once only)
  • For each request, construct an instance of javax.servlet.ServletRequest and an instance of 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.

The first servlet container for this chapter is not fully functional. Therefore, it cannot run other than very simple servlets and does not call the servlets' init and destroy methods. Instead, it does the following:

  • Wait for HTTP requests.
  • Construct a ServletRequest object and a ServletResponse object.
  • 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 the service method of the servlet, passing the ServletRequest and ServletResponse objects.

Note: In this servlet container, the servlet class is loaded every time the servlet is requested.

The first application consists of six classes:

  • HttpServer1
  • Request
  • Response
  • StaticResourceProcessor
  • ServletProcessor1
  • Constants

Figure 2.1 displays the UML diagram of the first servlet container.

Figure 2.1: The UML diagram of the first servlet container

The entry point of this application (the static main method) is in the HttpServer1 class. The main method creates an instance of HttpServer1 and calls its await method. The await method waits for HTTP requests, creates a Request object and a Response object for every request, and dispatch them either to a StaticResourceProcessor instance or a ServletProcessor instance, depending on whether the request is for a static resource or a servlet.

The Constants class contains the static final WEB_ROOT that is referenced from other classes. WEB_ROOT indicates the location of PrimitiveServlet and the static resource that can be served by this container.

The HttpServer1 instance keeps waiting for HTTP requests until a shutdown command is received. You issue a shutdown command the same way as you did it in Chapter 1.

Each of the classes in the application is discussed in the following sections.