3.1 A Brief Introduction to Servlets and JSP
3.1.1 The Servlet Architecture
When a Web server receives a client request for static web pages (usually files with an
extension .htm or .html), it looks for the requested page, and simply responds to the client with
the contents. However, when dynamic content is requested, the behavior of the server needs to
be different: In this case, a program has to be run on the server machine that interprets the
parameters of the request and generates the content accordingly. To enable the server to
distinguish between regular requests for static pages and requests for dynamic content, the
server needs to be made aware of which requests should map to a program. This is usually
done through a server plug in. This plug in is a small interface that tells the server which
requests are dynamic (e.g. all pages that end with .cgi or .jsp), and what program to forward
these requests to.
A popular way of generating dynamic content in the past was the Common Gateway Interface
(CGI). The CGI environment instantiates a new child process on the server to handle each
request, i.e. runs a program that generates the output dynamically. This method, however, is
very resource intensive. Creating a the new runtime environment, initializing it and destroying it
after use are overhead tasks that can weigh heavily when a Web server receives thousands of
requests per day. A large number of simultaneous requests could even cause the server to
crash due to memory restrictions.
Servlets offer a much lighter weight approach to handling many client requests. Although the
servlet interface definition is based on CGI, it processes requests differently. A single program
running on the server, a so called Servlet Engine or Servlet Container, handles all requests.
Instead of creating a new process for each request, the Servlet Engine uses Java's
multithreading capabilities to generate the dynamic page within the Servlet Engine's main
process. This approach results in a much better performance than the classical CGI approach.
The interoperation between the Web server, the Servlet Container, and the client browser is
illustrated in Figure 3.