All new Java web-tier technologies, such as JSP, JSF, and portlets, are defined on top of the API that started it all: the Servlet API. A servlet is a Java class that processes a request from a client and produces a response. Most implementations of the JSF specification use a servlet as the entry-point for the page requests, and some JSF-based applications may also include a few servlets and other classes defined by the servlet specification, such as listeners and filters.
The Servlet API is general enough to allow servlets to deal with any
request/response-based protocol, but it’s almost
exclusively used with HTTP. The API consists of two packages: the
javax.servlet package contains classes and
interfaces that are protocol-independent, while the
javax.servlet.http package provides HTTP-specific
extensions and utility classes.
This is the base class for most servlets. It contains empty default
implementations of two methods that can be overridden by a subclass
for initialization and release of internal resources used by a
init() method is called once
before the servlet is asked to process its first request, and the
destroy() method is called just before the
servlet is taken out of service.
The base class also provides default implementations of the request
processing methods, one for each HTTP request type:
). Most subclasses override the
doPost() methods (or at least one of them) to
handle the corresponding HTTP request types, but rely on the default
implementations for the other request types.
This interface represents the HTTP request, with methods for reading request parameters, headers, and the request URL. Other methods let you add, read, and remove application data—called request attributes—associated with the request. This mechanism comes in handy when the servlet delegates some of the processing (e.g., the rendering of the response) to another application class, as I describe later.
The web container loads the servlet class—either when the
container is started or when the first request for the servlet is
received—and calls its methods, converting raw HTTP request
HttpServletRequest objects and
HttpServletResponse objects into raw HTTP response
messages. It’s important to realize that the
container creates only one instance of each
servlet. This means that the servlet must be
thread safe—able to handle
multiple requests at the same time, each executing as a separate
thread through the servlet code.