Chapter 5 Server Pages
Chapter 5 Server Pages
Table of Contents
Chapter 5 ............................................................................................................................................................ 2
5. Server Pages ............................................................................................................................................... 2
5.1. Introduction ......................................................................................................................................... 2
5.2. Java Server Pages Overview ............................................................................................................... 2
5.3. First Java Server Page Examples ........................................................................................................ 3
5.4. Implicit ObjCP .................................................................................................................................... 4
5.5. Scripting .............................................................................................................................................. 5
5.5.1. Scripting Components.................................................................................................................. 5
5.5.2. Scripting Example........................................................................................................................ 6
5.6. Standard Action ................................................................................................................................... 8
5.6.1. <jsp:include> Action.................................................................................................................... 9
5.6.2. <jsp:forward> Action ................................................................................................................. 11
5.6.3. <jsp:plugin> Action ................................................................................................................... 13
5.6.4. <jsp:useBean> Action ................................................................................................................ 15
5.7. Directives .......................................................................................................................................... 24
5.7.1. page Directive ............................................................................................................................ 24
5.7.2. include Directive ........................................................................................................................ 25
Chapter 5
5. Server Pages
5.1. Introduction
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 reuse JavaBeans and create custom tag libraries that
encapsulate complex, dynamic functionality. Custom-tag libraries even enable Web-page designers who are
not familiar with Java to enhance Web pages with powerful dynamic content and processing capabilities. In
addition to the classes and interfaces for programming servlets (from packages javax.servlet and
javax.servlet.http), classes and interfaces specific to JavaServer Pages programming are located in packages
javax.servlet.jsp and javax.servlet.jsp.tagext.
There are four key components to JSPs: directives, actions, scriptlets and tag libraries. Directives are
messages to the JSP container that enable the programmer to specify page settings, to include content from
other resources and to specify custom tag libraries for use in a JSP. Actions encapsulate functionality in
predefined tags that programmers can embed in a JSP. Actions often are performed based on the information
sent to the server as part of a particular client request. They also can create Java objects for use in JSP scriptlets.
Scriptlets, or scripting elements, enable programmers to insert Java code that interacts with components in a
JSP (and possibly other Web application components) to perform request processing. Tag libraries are part of
the tag extension mechanism that enables programmers to create custom tags. Such tags enable programmers
to manipulate JSP content.
In many ways, Java Server Pages look like standard XHTML or XML documents. In fact, JSPs normally
include XHTML or XML markup. Such markup is known as fixed-template data or fixed-template text. Fixed
template data often help a programmer decide whether to use a servlet or a JSP. Programmers tend to use JSPs
when most of the content sent to the client is fixed template data and only a small portion of the content is
generated dynamically with Java code. Programmers use servlets when only a small portion of the content
sent to the client is fixed-template data. In fact, some servlets do not produce content. Rather, they perform a
task on behalf of the client, then invoke other servlets or JSPs to provide a response. Note that in most cases,
servlet and JSP technologies are interchangeable. As with servlets, JSPs normally execute as part of a Web
server. The server often is referred to as the JSP container.
When a JSP-enabled server receives the first request for a JSP, the JSP container translates that JSP into a
Java servlet that handles the current request and future requests to the JSP. If there are any errors compiling
the new servlet, these errors result in translation-time errors. The JSP container places the Java statements
that implement the JSP’s response in method _jspService at translation time. If the new servlet compiles
properly, the JSP container invokes method _jspService to process the request. The JSP may respond directly
to the request or may invoke other Web application components to assist in processing the request. Any errors
that occur during request processing are known as requesttime errors. Overall, the request/response
mechanism and life cycle of a JSP is the same as that of a servlet. JSPs can define methods jspInit and
jspDestroy (similar to servlet methods init and destroy), which the JSP container invokes when initializing a
JSP and terminating a JSP, respectively. JSP programmers can define these methods using JSP declarations—
part of the JSP scripting mechanism.
We begin our introduction to JavaServer Pages with a simple example in which the current date and time are
inserted into a Web page using a JSP expression. As you can see, most of clock.jsp consists of XHTML
markup. In cases like this, JSPs are easier to implement than servlets. In a servlet that performs the same task
as this JSP, each line of XHTML markup typically is a separate Java statement that outputs the string
representing the markup as part of the response to the client. Writing code to output markup can often lead to
errors. Most JSP editors provide syntax coloring to help programmers check that their markup follows proper
syntax.
The JSP generates an XHTML document that displays the current date and time. The key line in this JSP (line
30) is the expression <%= new java.util.Date() %>
JSP expressions are delimited by <%= and %>. This
particular expression creates a new instance of class
Date from package java.util. 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 that we use the XHTML meta element
on line 10 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 on line 30,
creating a new Date object with the server’s current
date and time.
Implicit objects provide programmers with access to many servlet capabilities in the context of a JavaServer
Page. Implicit objects have four scopes: application, page, request and session. The JSP and servlet container
application owns objects with application scope. Any servlet or 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 the request to another servlet or 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.
5.5. Scripting
JavaServer Pages often present dynamically generated content as part of an XHTML document sent to the
client in response to a request. In some cases, the content is static, but is output only if certain conditions are
met during a request. JSP programmers can insert Java code and logic in a JSP using scripting.
JSP scripting components include scriptlets, comments, expressions, declarations and escape sequences.
Scriptlets are blocks of code delimited by <% and %>. They contain Java statements that the container places
in method _jspService at translation time. JSPs support three comment styles: JSP comments, XHTML
comments and comments from the scripting language. JSP comments are delimited by <%-- and --%>. Such
Advanced Programming Chapter 5 Server Pages by Bantamlak Dejene 5
Samara University College of Engineering and Technology Department of Information Technology
comments can be placed throughout a JSP, but not inside scriptlets. XHTML comments are delimited with <!-
- and -->. These comments can be placed throughout a JSP, but not inside scriptlets. Scripting language
comments are currently Java comments, because Java is the only JSP scripting language at the present time.
Scriptlets can use Java’s single-line comments (delimited by/ and /) and multiline comments (delimited by /*
and */). JSP comments and scripting-language comments are ignored and do not appear in the response to a
client. When clients view the source code of a JSP response, they will see only the XHTML comments in the
source code. The different comment styles are useful for separating comments that the user should be able to
see from comments that document logic processed on the server.
A JSP expression, delimited by <%= and %>, contains a Java expression that is evaluated when a client
requests the JSP containing the expression. The container converts the result of a JSP expression to a String
object, then outputs the String as part of the response to the client. Declarations (delimited by <%! and %>)
enable a JSP programmer to define variables and methods. Variables become instance variables of the servlet
class that represents the translated JSP. Similarly, methods become members of the class that represents the
translated JSP. Declarations of variables and methods in a JSP use Java syntax. Thus, a variable declaration
must end in a semicolon, as in <%! int counter = 0; %>. Special characters or character sequences that the
JSP container normally uses to delimit JSP code can be included in a JSP as literal characters in scripting
elements, fixed template data and attribute values using escape sequences.
The JSP enables the user to input a first name, then outputs that name as part of the response. Using scripting,
the JSP determines whether a firstName parameter was passed to the JSP as part of the request; if not, the
JSP returns an XHTML document containing a form through which the user can input a first name. Otherwise,
the JSP obtains the firstName value and uses it as part of an XHTML document that welcomes the user to
JavaServer Pages.
the literal text in a JSP becomes string literals in the servlet that represents
the translated JSP.
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- Fig. 10.4: welcome.jsp -->
<!-- JSP that processes a "get" request containing data. -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<!-- head section of document -->
<head>
<title>Processing "get" requests with data</title>
</head>
<!-- body section of document -->
<body>
<% // begin scriptlet
String name = request.getParameter( "firstName" );
if ( name != null ) {
%> <%-- end scriptlet to insert fixed template data --%>
<h1>
Hello <%= name %>, <br />
Welcome to JavaServer Pages!
</h1>
<% // continue scriptlet
} // end if
else {
%> <%-- end scriptlet to insert fixed template data --%>
<form action = "welcome.jsp" method = "get">
<p>Type your first name and press Submit</p>
<p><input type = "text" name = "firstName" />
<input type = "submit" value = "Submit" />
</p>
</form>
<% // continue scriptlet
} // end else
%> <%-- end scriptlet --%>
</body>
</html> <!-- end XHTML document -->
Notice that the majority of the code is XHTML markup (i.e., fixed template data). Throughout the body
element are several scriptlets (lines 17–23, 30–
35 and 45–49) and a JSP expression (line 26).
Note that three comment styles appear in this
JSP. The scriptlets define an if/else structure that
determines whether the JSP received a value for
the first name as part of the request. Line 19 uses
method getParameter of JSP implicit object
request (an HttpServletRequest object) to
obtain the value for parameter firstName and
assigns the result to variable name. Line 21 determines if name is not null, (i.e., a value for the first name
was passed to the JSP as part of the request). If this condition is true, the scriptlet terminates temporarily so
the fixed template data at lines 25–28 can be output. The JSP expression in line 26 outputs the value of variable
name (i.e., the first name passed to the JSP as a request parameter. The scriptlet continues at lines 30–35 with
the closing curly brace of the if structure’s body and the beginning of the else part of the if/else structure. If
the condition at line 21 is false, lines 25–28 are not output. Instead, lines 37–43 output a form element. The
user can type a first name in the form and press the Submit button to request the JSP again and execute the if
structure’s body (lines 25–28).
JSP standard actions provide JSP implementors with access to several of the most common tasks performed
in a JSP, such as including content from other resources, forwarding requests to other resources and interacting
with JavaBeans. JSP containers process actions at request time. Actions are delimited by <jsp:action> and
</jsp:action>, where action is the standard action name. In cases where nothing appears between the starting
and ending tags, the XML empty element syntax <jsp:action /> can be used.
Action Description
<jsp:include> Dynamically includes another resource in a JSP. As the JSP executes, the referenced
resource is included and processed.
<jsp:forward> Forwards request processing to another JSP, servlet or static page.
This action terminates the current JSP’s execution.
<jsp:plugin> Allows a plug-in component to be added to a page in the form of a browser-specific
object or embed HTML element. In the case of a Java applet, this action enables the
downloading and installation of the Java Plug-in, if it is not already installed on the
client computer.
<jsp:param> Used with the include, forward and plugin actions to specify additional name/value
pairs of information for use by these actions.
JavaBean Manipulation
<jsp:useBean> Specifies that the JSP uses a JavaBean instance. This action specifies the scope of the
bean and assigns it an ID that scripting components can use to manipulate the bean.
<jsp:setProperty> Sets a property in the specified JavaBean instance. A special feature of this action is
automatic matching of request parameters to bean properties of the same name.
<jsp:getProperty> Gets a property in the specified JavaBean instance and converts the result to a string
for output in the response.
JavaServer Pages support two include mechanisms—the <jsp:include> action and the include directive.
Action <jsp:include> enables dynamic content to be included in a JavaServer Page. If the included resource
changes between requests, the next request to the JSP containing the <jsp:include> action includes the new
content of the resource. On the other hand, the include directive copies the content into the JSP once, at JSP
translation time. If the included resource changes, the new content will not be reflected in the JSP that used
the include directive unless that JSP is recompiled.
Attribute Description
Page Specifies the relative URI path of the resource to include. The resource must be part of the
same Web application.
flush Specifies whether the buffer should be flushed after the include is performed. In JSP 1.1,
this attribute is required to be true.
<! -- banner.html -->
<! -- banner to include in another document -->
<div style = "width: 580px">
<p>
Java(TM), C, C++, Visual Basic(R), Object Technology, and <br /> Internet and World Wide Web
Programming Training <br /> On-Site Seminars Delivered Worldwide
</p>
<p>
<a href = "mailto:[email protected]"> [email protected]</a><br /> 978.579.9911<br /> 490B Boston
Post Road, Suite 200, Sudbury, MA 01776
</p>
</div>
<!-- toc.html -->
<!-- contents to include in another document -->
<p><a href = "http://www.deitel.com/books/index.html"> Publications/Bookstore </a></p>
<p><a href = "http://www.deitel.com/whatsnew.html"> What's New </a></p>
<p><a href = "http://www.deitel.com/books/downloads.html"> Downloads/Resources</a></p>
<p><a href = "http://www.deitel.com/faq/index.html"> FAQ (Frequently Asked Questions)</a></p>
<p><a href = "http://www.deitel.com/intro.html"> Who we are </a></p>
<p><a href = "http://www.deitel.com/index.html"> Home Page </a></p>
<p>Send questions or comments about this site to
<a href = "mailto:[email protected]"> [email protected] </a><br />
Copyright 1995-2002 by Deitel & Associates, Inc. All Rights Reserved.
</p>
<!-- clock2.jsp -->
<!-- date and time to include in another document -->
<table>
<tr>
<td style = "background-color: black;">
<p class = "big" style = "color: cyan; font-size: 3em; font-weight: bold;">
<%-- script to determine client local and --%>
<%-- format date accordingly --%>
<%
Action <jsp:forward> enables a JSP to forward request processing to a different resource. Request processing
by the original JSP terminates as soon as the JSP forwards the request. Action <jsp:forward> has only a page
attribute that specifies the relative URI of the resource (in the same Web application) to which the request
should be forwarded. The <jsp:param> action specifies name/value pairs of information that are passed to
the <jsp:include>, <jsp:forward> and <jsp:plugin> actions. Every <jsp:param> action has two required
attributes: name and value. If a <jsp:param> action specifies a parameter that already exists in the request,
the new value for the parameter takes precedence over the original value. All values for that parameter can be
obtained by using the JSP implicit object request’s getParameterValues method, which returns an array of
Strings.
if ( name != null ) {
%> <%-- end scriptlet to insert fixed template data --%>
<jsp:forward page = "forward2.jsp">
<jsp:param name = "date"
value = "<%= new java.util.Date() %>" />
</jsp:forward>
<% // continue scriptlet
} // end if
else {
%> <%-- end scriptlet to insert fixed template data --%>
<form action = "forward1.jsp" method = "get">
<p>Type your first name and press Submit</p>
<p><input type = "text" name = "firstName" />
<input type = "submit" value = "Submit" />
</p>
</form>
<% // continue scriptlet
} // end else
%> <%-- end scriptlet --%>
</body>
</html> <!-- end XHTML document -->
</table>
</body>
</html>
Action <jsp:plugin> adds an applet or JavaBean to a Web page in the form of a browser-specific object or
embed XHTML element. This action also enables the client to download and install the Java Plug-in if it is
not already installed.
Attribute Description
type Component type—bean or applet.
code Class that represents the component.
codebase Location of the class specified in the code attribute and the archives specified in the
archive attribute.
align Alignment of the component.
archive A space-separated list of archive files that contain resources used by the component.
Such an archive may include the class specified by the code attribute.
height Component height in the page specified in pixels or percentage.
hspace Number of pixels of space that appear to the left and to the right of the component.
jreversion Version of the Java Runtime Environment and plug-in required to execute the
component. The default value is 1.1.
name Name of the component.
vspace Number of pixels of space that appear above and below the component.
title Text that describes the component.
width Component width in the page specified in pixels or percentage.
nspluginurl Location for download of the Java Plug-in for Netscape Navigator.
iepluginurl Location for download of the Java Plug-in for Internet Explorer.
// ShapesApplet.java
// Applet that demonstrates a Java2D GeneralPath.
package com.deitel.advjhtp1.jsp.applet;
<html>
<head>
<title>Using jsp:plugin to load an applet</title>
</head>
<body>
<jsp:plugin type = "applet" code = "com.deitel.advjhtp1.jsp.applet.ShapesApplet"
codebase = "/advjhtp1/jsp" width = "400" height = "400">
<jsp:params>
<jsp:param name = "red" value = "255" />
<jsp:param name = "green" value = "255" />
<jsp:param name = "blue" value = "0" />
</jsp:params>
</jsp:plugin>
</body>
</html>
Action <jsp:useBean> enables a JSP to manipulate a Java object. This action creates a Java object or locates
an existing object for use in the JSP. If attributes class and beanName are not specified, the JSP container
attempts to locate an existing object of the type specified in attribute type. Like JSP implicit objects, objects
specified with action <jsp:useBean> have page, request, session or application scope that indicates where
they can be used in a Web application. Objects with page scope are accessible only to the page in which they
are defined. Multiple JSP pages potentially can access objects with other scopes. For example, all JSPs that
process a single request can access an object with request scope. Many Web sites today place rotating
advertisements on their Web pages. Each visit to one of these pages typically results in a different
advertisement being displayed in the user’s Web browser. Typically, clicking an advertisement takes you to
the Web site of the company that placed the advertisement. Our first example of <jsp:useBean> demonstrates
a simple advertisement rotator bean that cycles through a list of five advertisements. In this example, the
advertisements are covers for some of our books. Clicking a cover takes you to the Amazon.com Web site
where you can read about and possibly order the book. The Rotator bean has three methods: getImage,
getLink and nextAd. Method getImage returns the image file name for the book cover image. Method
getLink returns the hyperlink to the book at Amazon.com. Method nextAd updates the Rotator so the next
calls to getImage and getLink return information for a different advertisement. Methods getImage and
getLink each represent a read-only JavaBean property—image and link, respectively. Rotator keeps track
of the current advertisement with its selectedIndex variable, which is updated by invoking method nextAd.
Attribute Description
id The name used to manipulate the Java object with actions <jsp:setProperty> and
<jsp:getProperty>. A variable of this name is also declared for use in JSP scripting elements.
The name specified here is case sensitive.
scope The scope in which the Java object is accessible—page, request, session or application. The
default scope is page.
class The fully qualified class name of the Java object.
beanName The name of a bean that can be used with method instantiate of class java.beans.Beans to
load a JavaBean into memory.
type The type of the JavaBean. This can be the same type as the class attribute, a superclass of that
type or an interface implemented by that type. The default value is the same as for attribute
class. A ClassCastException occurs if the Java object is not of the type specified with
attribute type.
// Rotator.java
// A JavaBean that rotates advertisements.
package com.deitel.advjhtp1.jsp.beans;
public class Rotator {
private String images[] = { "images/jhtp3.jpg", "images/xmlhtp1.jpg", "images/ebechtp1.jpg",
"images/iw3htp1.jpg", "images/cpphtp3.jpg" };
private String links[] = { "http://www.amazon.com/exec/obidos/ASIN/0130125075/" +
"deitelassociatin", "http://www.amazon.com/exec/obidos/ASIN/0130284173/" + "deitelassociatin",
"http://www.amazon.com/exec/obidos/ASIN/013028419X/" + "deitelassociatin",
"http://www.amazon.com/exec/obidos/ASIN/0130161438/" + "deitelassociatin",
19 "http://www.amazon.com/exec/obidos/ASIN/0130895717/" + "deitelassociatin" };
private int selectedIndex = 0;
// returns image file name for current ad
public String getImage()
{
return images[ selectedIndex ];
}
// returns the URL for ad's corresponding Web site
Attribute Description
name The ID of the JavaBean for which a property (or properties) will be set.
property The name of the property to set. Specifying "*" for this attribute causes the JSP to match the
request parameters to the properties of the bean. For each request parameter that matches (i.e.,
the name of the request parameter is identical to the bean’s property name), the corresponding
property in the bean is set to the value of the parameter. If the value of the request parameter
is "", the property value in the bean remains unchanged.
param If request parameter names do not match bean property names, this attribute can be used to
specify which request parameter should be used to obtain the value for a specific bean property.
This attribute is optional. If this attribute is omitted, the request parameter names must match
bean property names.
value The value to assign to a bean property. The value typically is the result of a JSP expression.
This attribute is particularly useful for setting bean properties that cannot be set using request
parameters. This attribute is optional. If this attribute is omitted, the JavaBean property must
be of a data type that can be set using request parameters.
// GuestBean.java
// JavaBean to store data for a guest in the guest book.
package com.deitel.advjhtp1.jsp.beans;
public class GuestBean {
private String firstName, lastName, email;
// set the guest's first name
public void setFirstName( String name )
{
firstName = name;
}
// get the guest's first name
public String getFirstName()
{
return firstName;
}
// set the guest's last name
public void setLastName( String name )
{
lastName = name;
}
// get the guest's last name
public String getLastName()
{
return lastName;
}
// set the guest's email address
public void setEmail( String address )
{
email = address;
}
// get the guest's email address
{
// attempt to close database connection
try {
getRecords.close();
addRecord.close();
connection.close();
}
// process SQLException on close operation
catch ( SQLException sqlException ) {
sqlException.printStackTrace();
}
}
}
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- guestBookLogin.jsp -->
<%-- page settings --%>
<%@ page errorPage = "guestBookErrorPage.jsp" %>
<%-- beans used in this JSP --%>
<jsp:useBean id = "guest" scope = "page" class = "com.deitel.advjhtp1.jsp.beans.GuestBean" />
<jsp:useBean id = "guestData" scope = "request" class = "com.deitel.advjhtp1.jsp.beans.GuestDataBean"
/>
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Guest Book Login</title>
<style type = "text/css">
body {
font-family: tahoma, helvetica, arial, sans-serif;
}
table, tr, td {
font-size: .9em;
border: 3px groove;
padding: 5px;
background-color: #dddddd;
}
</style>
</head>
<body>
<jsp:setProperty name = "guest" property = "*" />
<% // start scriptlet
if ( guest.getFirstName() == null ||
guest.getLastName() == null ||
guest.getEmail() == null ) {
%> <%-- end scriptlet to insert fixed template data --%>
<form method = "post" action = "guestBookLogin.jsp">
<p>Enter your first name, last name and email address to register in our guest book.</p>
<table>
<tr>
<td>First name</td>
<td>
<input type = "text" name = "firstName" />
</td>
</tr>
<tr>
<td>Last name</td>
<td>
<input type = "text" name = "lastName" />
</td>
</tr>
<tr>
<td>Email</td>
<td>
<input type = "text" name = "email" />
</td>
</tr>
<tr>
<td colspan = "2">
<input type = "submit"
value = "Submit" />
</td>
</tr>
</table>
</form>
<% // continue scriptlet
} // end if
else {
guestData.addGuest( guest );
%> <%-- end scriptlet to insert jsp:forward action --%>
<%-- forward to display guest book contents --%>
<jsp:forward page = "guestBookView.jsp" />
<% // continue scriptlet
} // end else
%> <%-- end scriptlet --%>
</body>
</html>
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- guestBookView.jsp -->
<%-- page settings --%>
<%@ page errorPage = "guestBookErrorPage.jsp" %>
<%@ page import = "java.util.*" %>
<%@ page import = "com.deitel.advjhtp1.jsp.beans.*" %>
<%-- GuestDataBean to obtain guest list --%>
<jsp:useBean id = "guestData" scope = "request" class = "com.deitel.advjhtp1.jsp.beans.GuestDataBean"
/>
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Guest List</title>
<style type = "text/css">
body {
font-family: tahoma, helvetica, arial, sans-serif;
}
table, tr, td, th {
text-align: center;
font-size: .9em;
border: 3px groove;
padding: 5px;
background-color: #dddddd;
}
</style>
</head>
<body>
<p style = "font-size: 2em;">Guest List</p>
<table>
<thead>
<tr>
<th style = "width: 100px;">Last name</th>
<th style = "width: 100px;">First name</th>
<th style = "width: 200px;">Email</th>
</tr>
</thead>
<tbody>
<% // start scriptlet
List guestList = guestData.getGuestList();
Iterator guestListIterator = guestList.iterator();
GuestBean guest;
while ( guestListIterator.hasNext() ) {
guest = ( GuestBean ) guestListIterator.next();
%> <%-- end scriptlet; insert fixed template data --%>
<tr>
<td><%= guest.getLastName() %></td>
<td><%= guest.getFirstName() %></td>
<td>
<a href = "mailto:<%= guest.getEmail() %>">
<%= guest.getEmail() %></a>
</td>
</tr>
<% // continue scriptlet
} // end while
%> <%-- end scriptlet --%>
</tbody>
</table>
</body>
</html>
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- guestBookErrorPage.jsp -->
<%-- page settings --%>
<%@ page isErrorPage = "true" %>
<%@ page import = "java.util.*" %>
<%@ page import = "java.sql.*" %>
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Error!</title>
<style type = "text/css">
.bigRed {
font-size: 2em;
color: red;
font-weight: bold;
}
</style>
</head>
<body>
<p class = "bigRed">
<% // scriptlet to determine exception type
// and output beginning of error message
if ( exception instanceof SQLException )
%>
An SQLException
<%
else if ( exception instanceof ClassNotFoundException )
%>
A ClassNotFoundException
<%
else
%>
An exception
<%-- end scriptlet to insert fixed template data --%>
<%-- continue error message output --%>
occurred while interacting with the guestbook database.
</p>
<p class = "bigRed">
The error message was:<br />
<%= exception.getMessage() %>
</p>
<p class = "bigRed">Please try again later</p>
</body>
</html>
5.7. Directives
Directives are messages to the JSP container that enable the programmer to specify page settings (such as the
error page), to include content from other resources and to specify custom-tag libraries for use in a JSP.
Directives (delimited by <%@ and %>) are processed at translation time. Thus, directives do not produce any
immediate output, because they are processed before the JSP accepts any requests.
The page directive specifies global settings for the JSP in the JSP container. There can be many page
directives, provided that there is only one occurrence of each attribute. The only exception to this rule is the
import attribute, which can be used repeatedly to import Java packages used in the JSP.
Directive Description
page Defines page settings for the JSP container to process.
include Causes the JSP container to perform a translation-time insertion of another resource’s
content. As the JSP is translated into a servlet and compiled, the referenced file replaces the
include directive and is translated as if it were originally part of the JSP.
taglib Allows programmers to include their own new tags in the form of tag libraries. These
libraries can be used to encapsulate functionality and simplify the coding of a JSP.
Attribute Description
language The scripting language used in the JSP. Currently, the only valid value for this
attribute is java.
extends Specifies the class from which the translated JSP will be inherited. This attribute must be
a fully qualified package and class name.
import Specifies a comma-separated list of fully qualified class names and/or packages that will
be used in the current JSP. When the scripting language is java, the default import list is
java.lang.*, javax.servlet.*, javax.servlet.jsp.* and javax.servlet.http.*. If multiple
import properties are specified, the package names are placed in a list by the container.
session Specifies whether the page participates in a session. The values for this attribute are true
(participates in a session—the default) or false (does not participate in a session). When
the page is part of a session, the JSP implicit object session is available for use in the page.
Otherwise, session is not available. In the latter case, using session in the scripting code
results in a translation-time error.
buffer Specifies the size of the output buffer used with the implicit object out. The value of this
attribute can be none for no buffering, or a value such as 8kb (the default buffer size).
The JSP specification indicates that the buffer used must be at least the size specified.
autoFlush When set to true (the default value), this attribute indicates that the output buffer used
with implicit object out should be flushed automatically when the buffer fills. If set to
false, an exception occurs if the buffer overflows. This attribute’s value must be true if
the buffer attribute is set to none.
isThreadSafe Specifies if the page is thread safe. If true (the default), the page is considered to be thread
safe, and it can process multiple requests at the same time. If false, the servlet that
represents the page implements interface java.lang.SingleThreadModel and only one
request can be processed by that JSP at a time. The JSP standard allows multiple instances
of a JSP to exists for JSPs that are not thread safe. This enables the container to handle
requests more efficiently. However, this does not guarantee that resources shared across
JSP instances are accessed in a thread-safe manner
info Specifies an information string that describes the page. This string is returned by the
getServletInfo method of the servlet that represents the translated JSP. This method can
be invoked through the JSP’s implicit page object.
errorPage Any exceptions in the current page that are not caught are sent to the error page for
processing. The error page implicit object exception references the original exception.
isErrorPage Specifies if the current page is an error page that will be invoked in response to an error
on another page. If the attribute value is true, the implicit object exception is created and
references the original exception that occurred. If false (the default), any use of the
exception object in the page results in a translation-time error.
contentType Specifies the MIME type of the data in the response to the client. The default
type is text/html.
The include directive includes the content of another resource once, at JSP translation time. The include
directive has only one attribute—file—that specifies the URL of the page to include. The difference between
directive include and action <jsp:include> is noticeable only if the included content changes. For example,
if the definition of an XHTML document changes after it is included with directive include, future invocations
of the JSP will show the original content of the XHTML document, not the new content. In contrast, action
<jsp:include> is processed in each request to the JSP. Therefore, changes to included content would be
apparent in the next request to the JSP that uses action <jsp:include>.