Apache Struts
S E R V L E T A N D J S P R E V I E W
13
JavaServer Pages (JSP)
Earlier, I mentioned that servlets are Java classes that generate an appropriate response
to an HTTP request. This response is usually an HTML page displaying the results of a
computation.
Unfortunately, a pure Java class is often not the easiest way to generate HTML. Your
typical web page contains lots of text, and your servlet subclass would have to contain or
access this text somewhere. In the worst-case scenario, you'd have Java classes containing
lots of text and HTML tags. And don't forget, you'd have to escape every double quote.
Trust me, it's not a pretty sight.
The problem is that Java classes (and therefore servlet subclasses) are code-centric, and
are not geared to allow the programmer to easily display large quantities of text, like a
web page.
JavaServer Pages (JSP) is a solution to this problem. A JSP page is text-centric, but allows
developers full access to the Java programming language via scriptlets. These consist of
Java code embedded in the JSP file between special marker tags, <% ... %>, as shown in
Listing 2-1.
Note
The servlet container (like Tomcat) actually converts a JSP page to a regular servlet, then compiles
it behind the scenes. This happens every time the JSP page is changed.
In the non-Java world, the closest analog to JSP would be PHP or Active Server Pages (ASP).
Listing 2-1 illustrates a simple JSP page, which I'll briefly analyze in the following
subsections:
Listing 2-1.
Hello.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="/tags/time" prefix="time" %>
<html>
<h1>Hello <%= "world".toUpperCase() %></h1>, and the time is now
<time:now format="hh:mm"/>.
</html>
Figure 2-5 shows how Hello.jsp might appear in the web browser.