Chapter 20. Servlets and JavaServer Pages
A
servlet is a Java class that implements the
javax.servlet.Servlet interface or, more commonly,
extends the abstract
javax.servlet.http.HttpServlet class. Servlets,
and the Java Servlet API, are an extension
architecture for web servers.[1] Instead of serving only static web pages, a
servlet-enabled web server can invoke servlet methods to dynamically
generate content at runtime. This model offers a number of advantages
over traditional CGI scripts. Notably, servlet instances can persist
across client requests, so the server is not constantly spawning
external processes.
[1] The
javax.servlet package can actually be used with
any type of server that implements a request/response protocol. Web
servers are currently the only common usage of servlets, however, and
this chapter discusses servlets in that context only.
JavaServer Pages (or JSP as it is commonly
called) is an architecture built on top of the servlet API. A JSP
page contains HTML or XML output intermingled with Java source code,
special JSP tags, and tags from imported "tag
libraries," including the very useful Java Standard
Tag Library, or JSTL. In JSP 2.0, JSP pages may also contain
expressions written in a simple "Expression
Language" (EL); these expressions are evaluated and
are replaced with their values. A JSP-enabled web server compiles JSP
pages on the fly, turning JSP source into servlets that produce
dynamic output.[2]
[2] It is worth noting that JSP is just
one of a general class of Java-based HTML templating tools. WebMacro
(webmacro.org) and Apache Velocity
(jakarta.apache.org/velocity) are popular
alternatives to JSP.
This chapter includes examples of both servlets and JSP pages and
concludes with an example "web
application" that uses Java objects, JSP pages, and
a coordinating servlet in a Model-View-Controller (MVC) architecture.
The chapter begins, however, by describing the prerequisites for
compiling, deploying, running, and serving servlets and JSP pages.
For more detailed information about servlets and JSP, see
Java Enterprise in a Nutshell, Java
Servlet Programming, by Jason Hunter with William
Crawford, and JavaServer Pages, by Hans
Bergsten, all published by O'Reilly.