AhmadLang / Java, How To Program, 2004
.pdf
[Page 1280]
Chapter 27. JavaServer Pages (JSP)
If it's a good script, I'll do it and if it's a bad script and they pay me enough, I'll do it.
George Burns
A fair request should be followed by the deed in silence.
Dante Alighieri
Talent is a question of quantity. Talent does not write one page: it writes three hundred.
Jules Renard
Every action must be due to one or other of seven causes: chance, nature, compulsion, habit, reasoning, anger, or appetite.
Aristotle
OBJECTIVES
In this chapter you will learn:
What JSPs are.
The differences between servlets and JSPs.
To create and deploy JavaServer Pages.
To use JSP's implicit objects and scriptlets to create dynamic Web pages.
To specify global JSP information with directives.
To use actions to manipulate JavaBeans in a JSP, to include resources dynamically and to forward requests to other JSPs.
[Page 1281]
Outline
27.1 Introduction
27.2 JavaServer Pages Overview
27.3 First JSP Example
27.4 Implicit Objects
27.5 Scripting
27.5.1 Scripting Components
27.5.2 Scripting Example
27.6 Standard Actions
27.6.1 <jsp:include> Action
27.6.2 <jsp:forward> Action
27.6.3 <jsp:useBean> Action
27.7 Directives
27.7.1 page Directive
27.7.2 include Directive
27.8 Case Study: Guest Book
27.9 Wrap-Up
27.10 Internet and Web Resources
Summary
Terminology
Self-Review Exercises
Answers to Self-Review Exercises Exercises
[Page 1281 (continued)]
27.1. Introduction
In Chapter 26, you learned how to generate dynamic Web pages with servlets. You probably have already noticed in our examples that most of the code in our servlets generated output that consisted of the HTML elements that composed the response to the client. Only a small portion of the code dealt with the business logic. Generating responses from servlets requires that Web application developers be familiar with Java. However, many people involved in Web application development, such as Web site designers, do not know Java. It is difficult for people who are not Java programmers to implement, maintain and extend a Web application that consists of primarily of servlets. The solution to this problem is JavaServer Pages (JSP)an extension of servlet technology that separates the presentation from the business logic. This lets Java programmers and Web-site designers focus on their strengthswriting Java code and designing Web pages, respectively.
JavaServer Pages simplify the delivery of dynamic Web content. They enable Web application programmers to create dynamic content by reusing predefined components and by interacting with components using server-side scripting. JavaServer Page programmers can use special software components called JavaBeans and custom tag libraries that encapsulate complex, dynamic functionality. A JavaBean is a reusable component that follows certain conventions for class design that are discussed in the JavaBeans specification, which is available at java.sun.com/products/javabeans/glasgow/index.html. Custom-tag libraries are a powerful feature of JSP that allows Java developers to hide complex code for database access and other useful services for dynamic Web pages in custom tags. Web sites use these custom tags like any other Web page element to take advantage of the more complex functionality hidden by the tag. Thus, Web-page designers who are not familiar with Java can enhance Web pages with powerful dynamic content and processing capabilities.
[Page 1282]
The classes and interfaces that are specific to JavaServer Pages programming are located in packages javax.servlet.jsp and javax.servlet.jsp.tagext. We discuss many of these classes and interfaces throughout this chapter as we present JSP fundamentals. For complete JSP details, see the JavaServer Pages 2.0 specification, which can be downloaded from java.sun.com/products/jsp/download.html. We also include other JSP resources in Section 27.10.
Overall, the request-response mechanism and the JSP life cycle are the same as those of a servlet. JSPs can override methods jspInit and jspDestroy (similar to servlet methods init and destroy), which the JSP container invokes when initializing and terminating a JSP, respectively. JSP programmers can define these methods using JSP declarationspart of the JSP scripting mechanism.
[Page 1283 (continued)]
27.3. First JSP Example
We begin our introduction to JavaServer Pages with a simple example, clock.jsp (Fig. 27.1), in which the current date and time are inserted into a Web page using a JSP expression.
Figure 27.1. JSP expression inserting the date and time into a Web page.
(This item is displayed on pages 1283 - 1284 in the print version)
1 |
<?xml version = "1.0"?> |
2 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" |
3 |
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> |
4 |
|
5 |
<!-- Fig. 27.1: clock.jsp --> |
6 |
|
7<html xmlns = "http://www.w3.org/1999/xhtml">
8<head>
9<meta http-equiv = "refresh" content = "60" />
10<title>A Simple JSP Example</title>
11<style type = "text/css">
12.big { font-family: helvetica, arial, sans-serif;
13 |
font-weight: bold; |
14 |
font-size: 2em; } |
15</style>
16</head>
17<body>
18<p class = "big">Simple JSP Example</p>
19<table style = "border: 6px outset;">
20<tr>
21 |
<td style = "background-color: black;"> |
|
22 |
<p |
class = "big" style = "color: cyan;"> |
23 |
|
<!-- JSP expression to insert date/time --> |
24 |
|
<%= new java.util.Date() %> |
25 |
</p> |
|
26 |
</td> |
|
27</tr>
28</table>
29</body>
30</html>
[View full size image]
[Page 1285]
The JSP in Fig. 27.1 generates an XHTML document that displays the current date and time. The key line in this JSP (line 24) is the expression
<%= new java.util.Date() %>
JSP expressions are delimited by <%= and %>. The preceding expression creates a new instance of class Date (package java.util). By default, a Date object is initialized with the current date and time. When the client requests this JSP, the preceding expression inserts the String representation of the date and time in the response to the client. [Note: Because the client of a JSP could be anywhere in the world, the JSP should return the date in the client locale's format. However, the JSP executes on the server, so the server's locale determines the String representation of the Date. In Fig. 27.10, clock2.jsp determines the client's locale, then uses a DateFormat (package java.text) object to format the date using that locale.]
Software Engineering Observation 27.3
The JSP container converts the result of every JSP expression into a string that is output as part of the response to the client.
We use the XHTML meta element in line 9 to set a refresh interval of 60 seconds for the document. This causes the browser to request clock.jsp every 60 seconds. For each request to clock.jsp, the JSP container reevaluates the expression in line 24, creating a new Date object with the server's current date and time.
As in Chapter 26, we use Apache Tomcat to test our JSPs in the jhtp6 Web application we created previously. For details on creating and configuring the jhtp6 Web application, review Section 26.3 and Section 26.4.1. To test clock.jsp, create a new directory called jsp in the jhtp6 subdirectory of Tomcat's webapps directory. Next, copy clock.jsp into the jsp directory. Open your Web browser and enter the following URL to test clock.jsp:
http://localhost:8080/jhtp6/jsp/clock.jsp
When you first invoke the JSP, you may notice a brief delay as Tomcat translates the JSP into a servlet and invokes the servlet to respond to your request. [Note: It is not necessary to create a directory named jsp in a Web application. We use this directory to separate the examples in this chapter from the servlet examples in Chapter 26.]
[Page 1285 (continued)]
27.4. Implicit Objects
Implicit objects provide access to many servlet capabilities in the context of a JavaServer Page. Implicit objects have four scopes: application, page, request and session. The JSP container owns objects with application scope. Any JSP can manipulate such objects. Objects with page scope exist only in the page that defines them. Each page has its own instances of the page-scope implicit objects. Objects with request scope exist for the duration of the request. For example, a JSP can partially process a request, then forward it to a servlet or another JSP for further processing. Request-scope objects go out of scope when request processing completes with a response to the client. Objects with session scope exist for the client's entire browsing session. Figure 27.2 describes the JSP implicit objects and their scopes. This chapter demonstrates several of these objects.
Figure 27.2. JSP implicit objects.
(This item is displayed on page 1286 in the print version)
Implicit object |
Description |
|
|
Application Scope |
|
application |
A javax.servlet.ServletContext object that represents the |
|
container in which the JSP executes. |
Page Scope |
|
config |
A javax.servlet.ServletConfig object that represents the JSP |
|
configuration options. As with servlets, configuration options can |
|
be specified in a Web application descriptor. |
exception |
A java.lang.Throwable object that represents an exception that |
|
is passed to a JSP error page. This object is available only in a |
|
JSP error page. |
out |
A javax.servlet.jsp.JspWriter object that writes text as part |
|
of the response to a request. This object is used implicitly with |
|
JSP expressions and actions that insert string content in a |
|
response. |
page |
An Object that represents the this reference for the current JSP |
|
instance. |
pageContext |
A javax.servlet.jsp.PageContext object that provides JSP |
|
programmers with access to the implicit objects discussed in this |
|
table. |
response |
An object that represents the response to the client and is |
|
normally an instance of a class that implements |
|
HttpServletResponse (package javax.servlet.http). If a |
|
protocol other than HTTP is used, this object is an instance of a |
|
class that implements javax.servlet.ServletResponse. |
Request Scope |
|
request |
An object that represents the client request and is normally an |
|
instance of a class that implements HttpServletRequest |
|
(package javax.servlet.http). If a protocol other than HTTP is |
|
used, this object is an instance of a subclass of |
|
javax.servlet.Servlet-Request. |
Session Scope |
|
session |
A javax.servlet.http.HttpSession object that represents the |
|
client session information if such a session has been created. |
This object is available only in pages that participate in a session.
[Page 1286]
Note that many of the implicit objects extend classes or implement interfaces discussed in Chapter 26. Thus, JSPs can use the same methods that servlets use to interact with such objects, as described in Chapter 26. Most of the examples in this chapter use one or more of the implicit objects in Fig. 27.2.
