2005 Pearson Education, Inc. All rights reserved. 1 27 JavaServer Pages (JSP)
-
Upload
katherine-greer -
Category
Documents
-
view
217 -
download
0
Transcript of 2005 Pearson Education, Inc. All rights reserved. 1 27 JavaServer Pages (JSP)
1
2005 Pearson Education, Inc. All rights reserved.
2727
JavaServer Pages (JSP)
2
2005 Pearson Education, Inc. All rights reserved.
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
3
2005 Pearson Education, Inc. All rights reserved.
OBJECTIVES
In this chapter you will learn: 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.
4
2005 Pearson Education, Inc. All rights reserved.
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
5
2005 Pearson Education, Inc. All rights reserved.
27.1 Introduction
• JavaServer Pages– Extension of Servlet technology– Separate the presentation from the business logic– Simplify the delivery of dynamic Web content– Reuse existing Java components
• JavaBean• Custom-tag libraries
– Encapsulate complex functionality
• Classes and interfaces specific to JSP– Package javax.servlet.jsp– Package javax.servlet.jsp.tagext
6
2005 Pearson Education, Inc. All rights reserved.
27.2 JavaServer Pages Overview
• Key components– Directives
– Actions
– Scripting elements
– Tag libraries
7
2005 Pearson Education, Inc. All rights reserved.
27.2 JavaServer Pages Overview (Cont.)
• Directive– Message to JSP container
• i.e., program that compiles/executes JSPs
– Enable programmers to specify• Page settings
• Content to include from other resources
• Custom tag libraries used in the JSP
8
2005 Pearson Education, Inc. All rights reserved.
27.2 JavaServer Pages Overview (Cont.)
• Action– Predefined JSP tags that encapsulate functionality
– Often performed based on information from client request
– Can be used to create Java objects for use in scriptlets
9
2005 Pearson Education, Inc. All rights reserved.
27.2 JavaServer Pages Overview (Cont.)
• Scripting elements– Enable programmers to insert Java code in JSPs
– Performs request processing• Interacts with page elements and other components to
implement dynamic pages
– Scriptlets• One kind of scripting element
• Contain code fragments
– Describe the action to be performed in response to user request
10
2005 Pearson Education, Inc. All rights reserved.
27.2 JavaServer Pages Overview (Cont.)
• Custom Tag Library– JSP’s tag extension mechanism
– Enables programmers to define new tags• Tags encapsulate complex functionality
– Tags can manipulate JSP content
11
2005 Pearson Education, Inc. All rights reserved.
27.2 JavaServer Pages Overview (Cont.)
• JSPs– Look like standard XHTML or XML
• Normally include XHTML or XML markup
– Known as fixed-template data
– Used when content is mostly fixed-template data• Small amounts of content generated dynamically
• Servlets– Used when small amount of content is fixed-template data
• Most content generated dynamically
12
2005 Pearson Education, Inc. All rights reserved.
Software Engineering Observation 27.1
Literal text in a JSP becomes string literals in the servlet that represents the translated JSP.
13
2005 Pearson Education, Inc. All rights reserved.
27.2 JavaServer Pages Overview (Cont.)
• When server receive the first JSP request– JSP container translates a JSP into a servlet
• Handle the current and future requests
• Code that represents the JSP– Placed in servlet’s _jspService method
• JSP errors – Translation-time errors
• Occur when JSPs are translated into servlets – Request-time errors
• Occur during request processing
• Methods jspInit and jspDestroy– Container invokes them when initializing and terminating a JSP– Defined in JSP declarations
14
2005 Pearson Education, Inc. All rights reserved.
Performance Tip 27.1
Some JSP containers translate JSPs to servlets at installation time. This eliminates the translation overhead for the first client that requests each JSP.
15
2005 Pearson Education, Inc. All rights reserved.
27.3 First JSP Example
• Simple JSP example (Fig. 27.1)– Demonstrates
• Fixed-template data (XHTML markup)• Creating a Java object (java.util.Date)• Automatic conversion of JSP expression to a String• meta element to refresh Web page at specified interval
– First invocation of clock.jsp• Notice the delay while:
– JSP container translates the JSP into a servlet– JSP container compiles the servlet– JSP container executes the servlet
• Subsequent invocations should not experience the same delay
16
2005 Pearson Education, Inc. All rights reserved.
Outline
clock.jsp
(1 of 2)
Line 9
Line 24
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>
meta element refreshes the Web page every 60 seconds
Creates Date object that is converted to a String
implicitly and displayed in paragraph (p) element
17
2005 Pearson Education, Inc. All rights reserved.
Outline
clock.jsp
(2 of 2)
Program output
18
2005 Pearson Education, Inc. All rights reserved.
Software Engineering Observation 27.2
JavaServer Pages are easier to implement than servlets when the response to a client request consists primarily of markup that remains constant between requests.
19
2005 Pearson Education, Inc. All rights reserved.
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.
20
2005 Pearson Education, Inc. All rights reserved.
27.4 Implicit Objects
• Implicit Objects– Provide access to many servlet capabilities within a
JSP
– Four scopes• Application scope
– Objects owned by the container application
– Any servlet or JSP can manipulate these objects
• Page scope
– Objects that exist only in page in which they are defined
– Each page has its own instance of these objects
21
2005 Pearson Education, Inc. All rights reserved.
27.4 Implicit Objects (Cont.)
• Request scope
– Objects exist for duration of client request
– Objects go out of scope when response sent to client
• Session scope
– Objects exist for duration of client’s browsing session
– Objects go out of scope when client terminates session or when session timeout occurs
22
2005 Pearson Education, Inc. All rights reserved.
Fig. 27.2 | JSP implicit objects. (1 of 2)
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.
23
2005 Pearson Education, Inc. All rights reserved.
Fig. 27.2 | JSP implicit objects. (2 of 2)
Implicit object Description
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 HttpServlet-Response (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.ServletRequest.
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.
24
2005 Pearson Education, Inc. All rights reserved.
27.5 Scripting
• Scripting– Dynamically generated content
– Insert Java code and logic in JSP using scripting
25
2005 Pearson Education, Inc. All rights reserved.
27.5.1 Scripting Components
• JSP scripting components– Scriptlets (delimited by <% and %>)
– Comments • JSP comments (delimited by <%-- and --%>)
• XHTML comments (delimited by <!-- and -->)
• Java’s comments (delimited by // and /* and */)
– Expressions (delimited by <%= and %>)
– Declarations (delimited by <%! and %>)
– Escape sequences
26
2005 Pearson Education, Inc. All rights reserved.
Common Programming Error 27.1
Placing a JSP comment or XHTML comment inside a scriptlet is a translation-time syntax error that prevents the JSP from being translated properly.
27
2005 Pearson Education, Inc. All rights reserved.
Software Engineering Observation 27.4
JSPs should not store client state information in instance variables. Rather, they should use the JSP implicit session object. For more information on how to use the session object, visit Sun’s J2EE tutorial at java.sun.com/j2ee/1.4/docs/tutorial/doc/index.html.
28
2005 Pearson Education, Inc. All rights reserved.
Fig. 27.3 | JSP escape sequences.
Literal
Escape sequence
Description
<% <\% The character sequence <% normally indicates the beginning of a scriptlet. The <\% escape sequence places the literal characters <% in the response to the client.
%> %\> The character sequence %> normally indicates the end of a scriptlet. The %\> escape sequence places the literal characters %> in the response to the client.
' " \
\' \" \\
As with string literals in a Java program, the escape sequences for characters ', " and \ allow these characters to appear in attribute values. Remember that the literal text in a JSP becomes string literals in the servlet that represents the translated JSP.
29
2005 Pearson Education, Inc. All rights reserved.
27.5.2 Scripting Example
• Demonstrate basic scripting capabilities– Responding to get requests
30
2005 Pearson Education, Inc. All rights reserved.
Software Engineering Observation 27.5
Scriptlets, expressions and fixed-template data can be intermixed in a JSP to create different responses based on the information in a request.
31
2005 Pearson Education, Inc. All rights reserved.
Outline
welcome.jsp
(1 of 3)
Lines 17-23
Line 19
Line 26
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.4: welcome.jsp -->
6 <!-- JSP that processes a "get" request containing data. -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9
10 <!-- head section of document -->
11 <head>
12 <title>Processing "get" requests with data</title>
13 </head>
14
15 <!-- body section of document -->
16 <body>
17 <% // begin scriptlet
18
19 String name = request.getParameter( "firstName" );
20
21 if ( name != null )
22 {
23 %> <%-- end scriptlet to insert fixed template data --%>
24
25 <h1>
26 Hello <%= name %>, <br />
27 Welcome to JavaServer Pages!
28 </h1>
29
Scriptlet used to insert Java code
Use request implicit object to get parameter
JSP expression
32
2005 Pearson Education, Inc. All rights reserved.
Outline
welcome.jsp
(2 of 3)
Lines 30-35 and lines 45-49
30 <% // continue scriptlet
31
32 } // end if
33 else {
34
35 %> <%-- end scriptlet to insert fixed template data --%>
36
37 <form action = "welcome.jsp" method = "get">
38 <p>Type your first name and press Submit</p>
39
40 <p><input type = "text" name = "firstName" />
41 <input type = "submit" value = "Submit" />
42 </p>
43 </form>
44
45 <% // continue scriptlet
46
47 } // end else
48
49 %> <%-- end scriptlet --%>
50 </body>
51
52 </html> <!-- end XHTML document -->
Scriptlets used to insert Java code
33
2005 Pearson Education, Inc. All rights reserved.
Outline
welcome.jsp
(3 of 3)
Program output
34
2005 Pearson Education, Inc. All rights reserved.
Error-Prevention Tip 27.1
It is sometimes difficult to debug errors in a JSP, because the line numbers reported by a JSP container normally refer to the servlet that represents the translated JSP, not the original JSP line numbers. Program development environments enable JSPs to be compiled in the environment, so you can see syntax error messages. These messages include the statement in the servlet that represents the translated JSP, which can be helpful in determining the error.
35
2005 Pearson Education, Inc. All rights reserved.
Error-Prevention Tip 27.2
Many JSP containers store the source code for the servlets that represent the translated JSPs. For example, the Tomcat installation directory contains a subdirectory called work in which you can find the source code for the servlets translated by Tomcat. Recall from Chapter 26 that the log files located in the logs subdirectory of the Tomcat installation directory are also helpful for determining the errors.
36
2005 Pearson Education, Inc. All rights reserved.
Error-Prevention Tip 27.3
Always put the closing brace for the if statement and the else in the same scriptlet.
37
2005 Pearson Education, Inc. All rights reserved.
27.6 Standard Actions
• JSP standard actions– Provide access to common tasks performed in a JSP
• Including content from other resources
• Forwarding requests to other resources
• Interacting with JavaBeans
– JSP containers process actions at request time
– Delimited by <jsp:action> and </jsp:action>
38
2005 Pearson Education, Inc. All rights reserved.
Fig. 27.5 | JSP standard actions. (1 of 2)
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 browser to download and install 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.
39
2005 Pearson Education, Inc. All rights reserved.
Fig. 27.5 | JSP standard actions. (2 of 2)
Action Description
JavaBean Manipulation <jsp:useBean> Specifies that the JSP uses a JavaBean instance (i.e., an object of the class
that declares the JavaBean). This action specifies the scope of the object and assigns it an ID (i.e., a variable name) 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.
40
2005 Pearson Education, Inc. All rights reserved.
27.6.1 <jsp:include> Action
•<jsp:include> action– Enables dynamic content to be included in a JSP
– More flexible than include directive• Requires more overhead when page contents change
frequently
41
2005 Pearson Education, Inc. All rights reserved.
Software Engineering Observation 27.6
According to the JavaServer Pages 2.0 specification, a JSP container is allowed to determine whether a resource included with the include directive has changed. If so, the container can recompile the JSP that included the resource. However, the specification does not provide a mechanism to indicate a change in an included resource to the container.
42
2005 Pearson Education, Inc. All rights reserved.
Performance Tip 27.2
The <jsp:include> action is more flexible than the include directive, but requires more overhead when page contents change frequently. Use the <jsp:include> action only when dynamic content is necessary.
43
2005 Pearson Education, Inc. All rights reserved.
Common Programming Error 27.2
Specifying in a <jsp:include> action a page that is not part of the same Web application is a request-time error—the <jsp:include> action will not include any content.
44
2005 Pearson Education, Inc. All rights reserved.
Fig. 27.6 | Action <jsp:include> attributes.
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 implicit object out should be flushed before the include is performed. If true, the JspWriter out is flushed prior to the inclusion, hence you could no longer forward to another page later on. The default value is false.
45
2005 Pearson Education, Inc. All rights reserved.
Outline
include.jsp
(1 of 3)
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.7: include.jsp -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8
9 <head>
10 <title>Using jsp:include</title>
11
12 <style type = "text/css">
13 body
14 {
15 font-family: tahoma, helvetica, arial, sans-serif;
16 }
17
18 table, tr, td
19 {
20 font-size: .9em;
21 border: 3px groove;
22 padding: 5px;
23 background-color: #dddddd;
24 }
25 </style>
26 </head>
27
46
2005 Pearson Education, Inc. All rights reserved.
Outline
include.jsp
(2 of 3)
Lines 38-39
Line 45
Lines 49-50
28 <body>
29 <table>
30 <tr>
31 <td style = "width: 160px; text-align: center">
32 <img src = "images/logotiny.png"
33 width = "140" height = "93"
34 alt = "Deitel & Associates, Inc. Logo" />
35 </td>
36 <td>
37 <%-- include banner.html in this JSP --%>
38 <jsp:include page = "banner.html"
39 flush = "true" />
40 </td>
41 </tr>
42 <tr>
43 <td style = "width: 160px">
44 <%-- include toc.html in this JSP --%>
45 <jsp:include page = "toc.html" flush = "true" />
46 </td>
47 <td style = "vertical-align: top">
48 <%-- include clock2.jsp in this JSP --%>
49 <jsp:include page = "clock2.jsp"
50 flush = "true" />
51 </td>
52 </tr>
53 </table>
54 </body>
55 </html>
Use JSP include action to include banner.html
Use JSP include action to include toc.html
Use JSP include action to include clock2.jsp
47
2005 Pearson Education, Inc. All rights reserved.
Outline
include.jsp
(3 of 3)
Program output
48
2005 Pearson Education, Inc. All rights reserved.
Outline
banner.html
1 <!-- Fig. 27.8: banner.html -->
2 <!-- banner to include in another document -->
3 <div style = "width: 580px">
4 <p>
5 Java(TM), C, C++, Visual Basic(R),
6 Object Technology, and <br /> Internet and
7 World Wide Web Programming Training <br />
8 On-Site Seminars Delivered Worldwide
9 </p>
10 <p>
11 <a href = "mailto:[email protected]">[email protected]</a>
12 <br />978.461.5880<br />12 Clock Tower Place, Suite 200,
13 Maynard, MA 01754
14 </p>
15 </div>
49
2005 Pearson Education, Inc. All rights reserved.
Outline
toc.html
1 <!-- Fig. 27.9: toc.html --> 2 <!-- contents to include in another document --> 3 4 <p><a href = "http://www.deitel.com/books/index.html"> 5 Publications/BookStore 6 </a></p> 7 8 <p><a href = "http://www.deitel.com/whatsnew.html"> 9 What's New 10 </a></p> 11 12 <p><a href = "http://www.deitel.com/books/downloads.html"> 13 Downloads/Resources 14 </a></p> 15 16 <p><a href = "http://www.deitel.com/faq/index.html"> 17 FAQ (Frequently Asked Questions) 18 </a></p> 19 20 <p><a href = "http://www.deitel.com/intro.html"> 21 Who we are 22 </a></p> 23 24 <p><a href = "http://www.deitel.com/index.html"> 25 Home Page 26 </a></p> 27 28 <p>Send questions or comments about this site to 29 <a href = "mailto:[email protected]"> 30 [email protected] 31 </a><br /> 32 Copyright 1995-2005 by Deitel & Associates, Inc. 33 All Rights Reserved. 34 </p>
50
2005 Pearson Education, Inc. All rights reserved.
Outline
clock2.jsp
Line 14
Lines 17-20
Line 25
1 <!-- Fig. 27.10: clock2.jsp -->
2 <!-- date and time to include in another document -->
3
4 <table>
5 <tr>
6 <td style = "background-color: black;">
7 <p class = "big" style = "color: cyan; font-size: 3em;
8 font-weight: bold;">
9
10 <%-- script to determine client local and --%>
11 <%-- format date accordingly --%>
12 <%
13 // get client locale
14 java.util.Locale locale = request.getLocale();
15
16 // get DateFormat for client's Locale
17 java.text.DateFormat dateFormat =
18 java.text.DateFormat.getDateTimeInstance(
19 java.text.DateFormat.LONG,
20 java.text.DateFormat.LONG, locale );
21
22 %> <%-- end script --%>
23
24 <%-- output date --%>
25 <%= dateFormat.format( new java.util.Date() ) %>
26 </p>
27 </td>
28 </tr>
29 </table>
Format Date with specified DataFormat
Use request object’s getLocale method to
obtain the client’s LocaleInvoke DateFormat static method getDateTimeInstance to obtain a DataFormat object for
the specified Locale
51
2005 Pearson Education, Inc. All rights reserved.
27.6.2 <jsp:forward> Action
•<jsp:forward> action– Enables JSP to forward request to different resources
• Forward requests to resources in same context
•<jsp:param> action– Specifies name-value pairs of information
• Name-value pairs are passed to other actions
52
2005 Pearson Education, Inc. All rights reserved.
Software Engineering Observation 27.7
When using the <jsp:forward> action, the resource to which the request will be forwarded must be in the same context (Web application) as the JSP that originally received the request.
53
2005 Pearson Education, Inc. All rights reserved.
Outline
forward1.jsp
(1 of 2)
Line 14
Lines 20-23
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.11: forward1.jsp -->t 6
7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Forward request to another JSP</title> 10 </head> 11 <body> 12 <% // begin scriptlet 13 14 String name = request.getParameter( "firstName" ); 15 16 if ( name != null ) 17 { 18 %> <%-- end scriptlet to insert fixed template data --%> 19
20 <jsp:forward page = "forward2.jsp"> 21 <jsp:param name = "date" 22 value = "<%= new java.util.Date() %>" /> 23 </jsp:forward> 24
25 <% // continue scriptlet 26 27 } // end if 28 else 29 { 30 %> <%-- end scriptlet to insert fixed template data --%>
Use request implicit object to get parameter
Forward request to forward2.jsp
54
2005 Pearson Education, Inc. All rights reserved.
Outline
forward1.jsp
(2 of 2)
Program output
31
32 <form action = "forward1.jsp" method = "get"> 33 <p>Type your first name and press Submit</p> 34
35 <p><input type = "text" name = "firstName" /> 36 <input type = "submit" value = "Submit" /> 37 </p> 38 </form> 39
40 <% // continue scriptlet 41 42 } // end else 43 44 %> <%-- end scriptlet --%> 45 </body> 46 </html> <!-- end XHTML document -->
55
2005 Pearson Education, Inc. All rights reserved.
Outline
forward2.jsp
(1 of 2)
Line 21
Line 28
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.12: forward2.jsp --> 6 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Processing a forwarded request</title> 10 <style type = "text/css"> 11 .big 12 { 13 font-family: tahoma, helvetica, arial, sans-serif; 14 font-weight: bold; 15 font-size: 2em; 16 } 17 </style> 18 </head> 19 <body> 20 <p class = "big"> 21 Hello <%= request.getParameter( "firstName" ) %>, <br /> 22 Your request was received <br /> and forwarded at 23 </p> 24 <table style = "border: 6px outset;"> 25 <tr> 26 <td style = "background-color: black;"> 27 <p class = "big" style = "color: cyan;"> 28 <%= request.getParameter( "date" ) %> 29 </p> 30 </td> 31 </tr> 32 </table> 33 </body> 34 </html>
Receive request from forward1.jsp, then
get firstName parameter from request
Get date parameter from request
56
2005 Pearson Education, Inc. All rights reserved.
Outline
forward2.jsp
(2 of 2)
Program output
57
2005 Pearson Education, Inc. All rights reserved.
27.6.3 <jsp:useBean> Action
•<jsp:useBean> action– Enables JSP to manipulate Java object
• Creates Java object or locates an existing object for use in JSP
58
2005 Pearson Education, Inc. All rights reserved.
Common Programming Error 27.3
One or both of the <jsp:useBean> attributes class and type must be specified—otherwise, a translation-time error occurs.
59
2005 Pearson Education, Inc. All rights reserved.
Fig. 27.13 | Attributes of the <jsp:useBean> action.
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 JavaBean 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.
60
2005 Pearson Education, Inc. All rights reserved.
Outline
Rotator.java
(1 of 2)
Lines 26-29
1 // Fig. 27.14: Rotator.java 2 // A JavaBean that rotates advertisements. 3 package com.deitel.jhtp6.jsp.beans; 4
5 public class Rotator 6 { 7 private String images[] = { "images/advjHTP1.jpg", 8 "images/cppHTP4.jpg", "images/iw3HTP2.jpg", 9 "images/jwsFEP1.jpg", "images/vbnetHTP2.jpg" }; 10 11 private String links[] = { 12 "http://www.amazon.com/exec/obidos/ASIN/0130895601/" + 13 "deitelassociatin", 14 "http://www.amazon.com/exec/obidos/ASIN/0130384747/" + 15 "deitelassociatin", 16 "http://www.amazon.com/exec/obidos/ASIN/0130308978/" + 17 "deitelassociatin", 18 "http://www.amazon.com/exec/obidos/ASIN/0130461342/" + 19 "deitelassociatin", 20 "http://www.amazon.com/exec/obidos/ASIN/0130293636/" + 21 "deitelassociatin" }; 22 23 private int selectedIndex = 0; 24
25 // returns image file name for current ad 26 public String getImage() 27 { 28 return images[ selectedIndex ]; 29 } // end method getImage 30
Return image file name for book cover image
61
2005 Pearson Education, Inc. All rights reserved.
Outline
Rotator.java
(2 of 2)
Lines 32-35
Lines 39-42
31 // returns the URL for ad's corresponding Web site
32 public String getLink()
33 {
34 return links[ selectedIndex ];
35 } // end method getLink
36
37 // update selectedIndex so next calls to getImage and
38 // getLink return a different advertisement
39 public void nextAd()
40 {
41 selectedIndex = ( selectedIndex + 1 ) % images.length;
42 } // end method nextAd
43 } // end class Rotator
Return hyperlink to book at Amazon.com
Update Rotator so subsequent calls to
getImage and getLink return information for
different advertisements
62
2005 Pearson Education, Inc. All rights reserved.
Outline
adrotator.jsp
(1 of 2)
Lines 7-8
Line 19
Lines 24-29
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.15: adrotator.jsp -->
6
7 <jsp:useBean id = "rotator" scope = "session"
8 class = "com.deitel.jhtp6.jsp.beans.Rotator" />
9
10 <html xmlns = "http://www.w3.org/1999/xhtml">
11 <head>
12 <title>AdRotator Example</title>
13 <style type = "text/css">
14 .big { font-family: helvetica, arial, sans-serif;
15 font-weight: bold;
16 font-size: 2em }
17 </style>
18 <%-- update advertisement --%>
19 <% rotator.nextAd(); %>
20 </head>
21 <body>
22 <p class = "big">AdRotator Example</p>
23 <p>
24 <a href = "<jsp:getProperty name = "rotator"
25 property = "link" />">
26
27 <img src = "<jsp:getProperty name = "rotator"
28 property = "image" />" alt = "advertisement" />
29 </a>
30 </p>
31 </body>
32 </html>
Use jsp:useBean action to obtain reference
to Rotator object
Invoke Rotator’s nextAd method
Define hyperlink to Amazon.com site
63
2005 Pearson Education, Inc. All rights reserved.
Outline
adrotator.jsp
(2 of 2)
Program output
64
2005 Pearson Education, Inc. All rights reserved.
27.6.3 <jsp:useBean> Action (Cont.)
• Action <jsp:getProperty>– Attribute name
• Specify the bean object to manipulate
– Attribute property• Specify the property to get
– Replace <jsp:getProperty> action with JSP expressions• <%= rotator.getLink() %>
• <%= rotator.getImage() %>
65
2005 Pearson Education, Inc. All rights reserved.
Software Engineering Observation 27.8
Action <jsp:setProperty> can use request-parameter values to set JavaBean properties of the following types: Strings, primitive types (boolean, byte, char, short, int, long, float and double) and type-wrapper classes (Boolean, Byte, Character, Short, Integer, Long, Float and Double). See Fig. 27.22 for an example.
66
2005 Pearson Education, Inc. All rights reserved.
Fig. 27.16 | Attributes of the <jsp:setProperty> action.
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 specifies that the JSP should 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 the 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 type that can be set using request parameters.
67
2005 Pearson Education, Inc. All rights reserved.
Common Programming Error 27.4
Conversion errors occur if you use action <jsp:setProperty>’s value attribute to set JavaBean property types that cannot be set with request parameters.
68
2005 Pearson Education, Inc. All rights reserved.
27.7 Directives
• JSP directives– Messages to JSP container
– Enable programmer to:• Specify page settings
• Include content from other resources
• Specify custom-tag libraries
– Delimited by <%@ and %>
69
2005 Pearson Education, Inc. All rights reserved.
Fig. 27.17 | JSP directives.
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 use new tags from tag libraries that encapsulate more complex functionality and simplify the coding of a JSP.
70
2005 Pearson Education, Inc. All rights reserved.
27.7.1 page Directive
• JSP page directive– Specifies JSP’s global settings in JSP container
71
2005 Pearson Education, Inc. All rights reserved.
Common Programming Error 27.5
Providing multiple page directives with one or more repeated attributes in common is a JSP translation-time error, unless the values for all repeated attributes are identical. Also, providing a page directive with an attribute or value that is not recognized is a JSP translation-time error.
72
2005 Pearson Education, Inc. All rights reserved.
Software Engineering Observation 27.9
According to the JSP specification, section 1.10.1, the extends attribute “should not be used without careful consideration as it restricts the ability of the JSP container to provide specialized superclasses that may improve on the quality of rendered service.” Remember that a Java class can extend exactly one other class. If your JSP specifies an explicit superclass, the JSP container cannot translate your JSP into a subclass of one of the container application’s own enhanced servlet classes.
73
2005 Pearson Education, Inc. All rights reserved.
Fig. 27.18 | Attributes of the page directive. (1 or 3)
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 can inherit. This attribute must be a fully qualified class name.
import Specifies a comma-separated list of fully qualified type 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, implicit object session is available for use in the page. Otherwise, session is not available, and 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.
74
2005 Pearson Education, Inc. All rights reserved.
Fig. 27.18 | Attributes of the page directive. (2 or 3)
Attribute Description
autoFlush When set to true (the default), 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 whether 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 exist 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.
75
2005 Pearson Education, Inc. All rights reserved.
Fig. 27.18 | Attributes of the page directive. (3 or 3)
Attribute Description
isErrorPage Specifies whether 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.
pageEncoding Specifies the character encoding of the JSP page. The default value is ISO-8859-1.
isELIgnored Specifies whether JSP container should evaluate expressions that use the Expression Language (EL)—a new feature in JSP 2.0 that allows JSP authors to create scriptless JSP pages. EL is typically used with JSP tag libraries, which are beyond the scope of this book. An EL expression has the form ${exp}. If the attribute value is true, the EL expressions are ignored, which means that the JSP container does not evaluate the expressions at translation time. If false, the EL expressions are evaluated by the JSP container. For more information on EL, visit java.sun.com/developer/EJTechTips/2004/tt0126.html
76
2005 Pearson Education, Inc. All rights reserved.
Common Programming Error 27.6
Using JSP implicit object session in a JSP that does not have its page directive attribute session set to true is a translation-time error.
77
2005 Pearson Education, Inc. All rights reserved.
27.7.2 include Directive
• JSP include directive– Includes content of another resource at JSP translation
time• Not as flexible as <jsp:include> action
78
2005 Pearson Education, Inc. All rights reserved.
Outline
includeDirective.jsp
(1 of 3)
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.19: includeDirective.jsp -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Using the include directive</title>
10 <style type = "text/css">
11 body
12 {
13 font-family: tahoma, helvetica, arial, sans-serif;
14 }
15 table, tr, td
16 {
17 font-size: .9em;
18 border: 3px groove;
19 padding: 5px;
20 background-color: #dddddd;
21 }
22 </style>
23 </head>
24 <body>
79
2005 Pearson Education, Inc. All rights reserved.
Outline
includeDirective.jsp
(2 of 3)
Line 34
Line 40
Line 44
25 <table>
26 <tr>
27 <td style = "width: 160px; text-align: center">
28 <img src = "images/logotiny.png"
29 width = "140" height = "93"
30 alt = "Deitel & Associates, Inc. Logo" />
31 </td>
32 <td>
33 <%-- include banner.html in this JSP --%>
34 <%@ include file = "banner.html" %>
35 </td>
36 </tr>
37 <tr>
38 <td style = "width: 160px">
39 <%-- include toc.html in this JSP --%>
40 <%@ include file = "toc.html" %>
41 </td>
42 <td style = "vertical-align: top">
43 <%-- include clock2.jsp in this JSP --%>
44 <%@ include file = "clock2.jsp" %>
45 </td>
46 </tr>
47 </table>
48 </body>
49 </html>
Use include directive to include banner.html
Use include directive to include toc.html
Use include directive to include clock2.jsp
80
2005 Pearson Education, Inc. All rights reserved.
Outline
includeDirective.jsp
(3 of 3)
Program output
81
2005 Pearson Education, Inc. All rights reserved.
27.8 Case Study: Guest Book
• Demonstrate– Action <jsp:setProperty>
– JSP page directive
– JSP error pages
– Use of JDBC
82
2005 Pearson Education, Inc. All rights reserved.
Outline
GuestBean.java
(1 of 2)
Lines 7-9
1 // Fig. 27.20: GuestBean.java
2 // JavaBean to store data for a guest in the guest book.
3 package com.deitel.jhtp6.jsp.beans;
4
5 public class GuestBean
6 {
7 private String firstName;
8 private String lastName;
9 private String email;
10
11 // set the guest's first name
12 public void setFirstName( String name )
13 {
14 firstName = name;
15 } // end method setFirstName
16
17 // get the guest's first name
18 public String getFirstName()
19 {
20 return firstName;
21 } // end method getFirstName
22
GuestBean declares three guest properties: firstName, lastName and email
83
2005 Pearson Education, Inc. All rights reserved.
Outline
GuestBean.java
(2 of 2)
23 // set the guest's last name
24 public void setLastName( String name )
25 {
26 lastName = name;
27 } // end method setLastName
28
29 // get the guest's last name
30 public String getLastName()
31 {
32 return lastName;
33 } // end method getLastName
34
35 // set the guest's email address
36 public void setEmail( String address )
37 {
38 email = address;
39 } // end method setEmail
40
41 // get the guest's email address
42 public String getEmail()
43 {
44 return email;
45 } // end method getEmail
46 } // end class GuestBean
84
2005 Pearson Education, Inc. All rights reserved.
Outline
GuestDataBean.java
(1 of 3)
Line 19
Line 22
Line 23
Line 24
Line 25
1 // Fig. 27.21: GuestDataBean.java
2 // Class GuestDataBean makes a database connection and supports
3 // inserting and retrieving data from the database.
4 package com.deitel.jhtp6.jsp.beans;
5
6 import java.sql.SQLException;
7 import javax.sql.rowset.CachedRowSet;
8 import java.util.ArrayList;
9 import com.sun.rowset.CachedRowSetImpl; // CachedRowSet implementation
10
11 public class GuestDataBean
12 {
13 private CachedRowSet rowSet;
14
15 // construct GuestDataBean object
16 public GuestDataBean() throws Exception
17 {
18 // load the MySQL driver
19 Class.forName( "com.mysql.jdbc.Driver" );
20
21 // specify properties of CachedRowSet
22 rowSet = new CachedRowSetImpl();
23 rowSet.setUrl( "jdbc:mysql://localhost/guestbook" );
24 rowSet.setUsername( "jhtp6" );
25 rowSet.setPassword( "jhtp6" );
26
Load MySQL driver
Create a CachedRowSet object using Sun’s reference implementation
CachedRowSetImplSet the CachedRowSet’s
database URL propertySet the CachedRowSet’s database username propertySet the CachedRowSet’s database password property
85
2005 Pearson Education, Inc. All rights reserved.
Outline
GuestDataBean.java
(2 of 3)
Lines 28-29
Line 30
Line 38
Lines 41-50
27 // obtain list of titles
28 rowSet.setCommand(
29 "SELECT firstName, lastName, email FROM guests" );
30 rowSet.execute();
31 } // end GuestDataBean constructor
32
33 // return an ArrayList of GuestBeans
34 public ArrayList< GuestBean > getGuestList() throws SQLException
35 {
36 ArrayList< GuestBean > guestList = new ArrayList< GuestBean >();
37
38 rowSet.beforeFirst(); // move cursor before the first row
39
40 // get row data
41 while ( rowSet.next() )
42 {
43 GuestBean guest = new GuestBean();
44
45 guest.setFirstName( rowSet.getString( 1 ) );
46 guest.setLastName( rowSet.getString( 2 ) );
47 guest.setEmail( rowSet.getString( 3 ) );
48
49 guestList.add( guest );
50 } // end while
51
52 return guestList;
53 } // end method getGuestList
54
Set the CachedRowSet’s database command propertyExecute the query specified
by the command property
Move the CachedRowSet’s cursor before the first row
Create the GuestBean objects for each row in the CachedRowSet
86
2005 Pearson Education, Inc. All rights reserved.
Outline
GuestDataBean.java
(3 of 3)
Line 58
Lines 61-63
Line 64
Line 65
Line 66
55 // insert a guest in guestbook database
56 public void addGuest( GuestBean guest ) throws SQLException
57 {
58 rowSet.moveToInsertRow(); // move cursor to the insert row
59
60 // update the three columns of the insert row
61 rowSet.updateString( 1, guest.getFirstName() );
62 rowSet.updateString( 2, guest.getLastName() );
63 rowSet.updateString( 3, guest.getEmail() );
64 rowSet.insertRow(); // insert row to rowSet
65 rowSet.moveToCurrentRow(); // move cursor to the current row
66 rowSet.acceptChanges(); // propagate changes to database
67 } // end method addGuest
68 } // end class GuestDataBean
Invoke the CachedRowSet’s moveToInsertRow method to
remember the current row and move the cursor to the insert row
Invoke the CachedRowSet’s updateString method to
update the column valuesInvoke the CachedRowSet’s insertRow method to insert
the row into the rowsetInvoke the CachedRowSet’s
moveToCurrentRow method to move the cursor back to the current row
Invoke the CachedRowSet’s acceptChanges method to propagates the changes in the rowset to
the underlying database
87
2005 Pearson Education, Inc. All rights reserved.
Outline
guestBookLogin.jsp
(1 of 3)
Line 8
Lines 11-14
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.22: guestBookLogin.jsp --> 6 7 <%-- page settings --%> 8 <%@ page errorPage = "guestBookErrorPage.jsp" %> 9 10 <%-- beans used in this JSP --%> 11 <jsp:useBean id = "guest" scope = "page" 12 class = "com.deitel.jhtp6.jsp.beans.GuestBean" /> 13 <jsp:useBean id = "guestData" scope = "request" 14 class = "com.deitel.jhtp6.jsp.beans.GuestDataBean" /> 15 16 <html xmlns = "http://www.w3.org/1999/xhtml"> 17 <head> 18 <title>Guest Book Login</title> 19 <style type = "text/css"> 20 body 21 { 22 font-family: tahoma, helvetica, arial, sans-serif; 23 } 24 table, tr, td 25 { 26 font-size: .9em; 27 border: 3px groove; 28 padding: 5px; 29 background-color: #dddddd; 30 } 31 </style> 32 </head> 33 <body>
page directive defines information that is
globally available in JSP
Use jsp:useBean actions to obtain references
to GuestBean and GuestDataBean objects
88
2005 Pearson Education, Inc. All rights reserved.
Outline
guestBookLogin.jsp
(2 of 3)
Line 34
Lines 36-89
34 <jsp:setProperty name = "guest" property = "*" />
35 <% // start scriptlet
36 if ( guest.getFirstName() == null ||
37 guest.getLastName() == null ||
38 guest.getEmail() == null )
39 {
40 %> <%-- end scriptlet to insert fixed template data --%>
41 <form method = "post" action = "guestBookLogin.jsp">
42 <p>Enter your first name, last name and email
43 address to register in our guest book.</p>
44 <table>
45 <tr>
46 <td>First name</td>
47 <td>
48 <input type = "text" name = "firstName" />
49 </td>
50 </tr>
51 <tr>
52 <td>Last name</td>
53 <td>
54 <input type = "text" name = "lastName" />
55 </td>
56 </tr>
57 <tr>
58 <td>Email</td>
59 <td>
60 <input type = "text" name = "email" />
61 </td>
62 </tr>
Set properties of GuestBean with request parameter values, because the input elements have the same names as the GuestBean properties
Verify that the user fills in all the entries, including first name, last name and email
89
2005 Pearson Education, Inc. All rights reserved.
Outline
guestBookLogin.jsp
(3 of 3)
Line 74
Line 77
63 <tr>
64 <td colspan = "2">
65 <input type = "submit" value = "Submit" />
66 </td>
67 </tr>
68 </table>
69 </form>
70 <% // continue scriptlet
71 } // end if
72 else
73 {
74 guestData.addGuest( guest );
75 %> <%-- end scriptlet to insert jsp:forward action --%>
76 <%-- forward to display guest book contents --%>
77 <jsp:forward page = "guestBookView.jsp" />
78 <% // continue scriptlet
79 } // end else
80 %> <%-- end scriptlet --%>
81 </body>
82 </html>
Forward request to guestBookView.jsp
Add GuestBean guest to GuestDataBean guestData
90
2005 Pearson Education, Inc. All rights reserved.
27.8 Case Study: Guest Book (Cont.)
• Line 34– Specify “*” for attribute property– Match request parameters to properties– Can set the properties individually
• <jsp:setProperty name = “guest” property = “firstName” param = “firstName” />
• <jsp:setProperty name = “guest” property = “lastName” param = “lastName” />
• <jsp:setProperty name = “guest” property = “email” param = “email” />
• <% guest.setFirstName( request.getParameter( “firstName” ) ); %>
91
2005 Pearson Education, Inc. All rights reserved.
Outline
guestBookView.jsp
(1 of 2)
Lines 9 and 10
Lines 13-14
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.23: guestBookView.jsp --> 6 7 <%-- page settings --%> 8 <%@ page errorPage = "guestBookErrorPage.jsp" %> 9 <%@ page import = "java.util.*" %> 10 <%@ page import = "com.deitel.jhtp6.jsp.beans.*" %> 11 12 <%-- GuestDataBean to obtain guest list --%> 13 <jsp:useBean id = "guestData" scope = "request" 14 class = "com.deitel.jhtp6.jsp.beans.GuestDataBean" /> 15 16 <html xmlns = "http://www.w3.org/1999/xhtml"> 17 <head> 18 <title>Guest List</title> 19 <style type = "text/css"> 20 body 21 { 22 font-family: tahoma, helvetica, arial, sans-serif; 23 } 24 table, tr, td, th 25 { 26 text-align: center; 27 font-size: .9em; 28 border: 3px groove; 29 padding: 5px; 30 background-color: #dddddd; 31 } 32 </style> 33 </head>
Use page directive import to specify Java classes and packages that are used in JSP context
Use jsp:useBean action to obtain reference
to GuestDataBean
92
2005 Pearson Education, Inc. All rights reserved.
Outline
guestBookView.jsp
(2 of 2)
Lines 45-64
34 <body> 35 <p style = "font-size: 2em;">Guest List</p> 36 <table> 37 <thead> 38 <tr> 39 <th style = "width: 100px;">Last name</th> 40 <th style = "width: 100px;">First name</th> 41 <th style = "width: 200px;">Email</th> 42 </tr> 43 </thead> 44 <tbody> 45 <% // start scriptlet 46 List guestList = guestData.getGuestList(); 47 Iterator guestListIterator = guestList.iterator(); 48 GuestBean guest; 49 50 while ( guestListIterator.hasNext() ) 51 { 52 guest = ( GuestBean ) guestListIterator.next(); 53 %> <%-- end scriptlet; insert fixed template data --%> 54 <tr> 55 <td><%= guest.getLastName() %></td> 56 <td><%= guest.getFirstName() %></td> 57 <td> 58 <a href = "mailto:<%= guest.getEmail() %>"> 59 <%= guest.getEmail() %></a> 60 </td> 61 </tr> 62 <% // continue scriptlet 63 } // end while 64 %> <%-- end scriptlet --%> 65 </tbody> 66 </table> 67 </body> 68 </html>
Use scriptlet and expressions to display last name, first name and
email address for all guests
93
2005 Pearson Education, Inc. All rights reserved.
Outline
guestBookErrorPage.jsp
(1 of 3)
Line 8
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.24: guestBookErrorPage.jsp -->
6
7 <%-- page settings --%>
8 <%@ page isErrorPage = "true" %>
9 <%@ page import = "java.util.*" %>
10 <%@ page import = "java.sql.*" %>
11
12 <html xmlns = "http://www.w3.org/1999/xhtml">
13 <head>
14 <title>Error!</title>
15 <style type = "text/css">
16 .bigRed
17 {
18 font-size: 2em;
19 color: red;
20 font-weight: bold;
21 }
22 </style>
23 </head>
Use page directive isErrorPage to specify that guestBookError-Page is an error page
94
2005 Pearson Education, Inc. All rights reserved.
Outline
guestBookErrorPage.jsp
(2 of 3)
Lines 28 and 36
24 <body>
25 <p class = "bigRed">
26 <% // scriptlet to determine exception type
27 // and output beginning of error message
28 if ( exception instanceof SQLException )
29 {
30 %>
31
32 A SQLException
33
34 <%
35 } // end if
36 else if ( exception instanceof ClassNotFoundException )
37 {
38 %>
39
40 A ClassNotFoundException
41
42 <%
43 } // end else if
44 else
45 {
46 %>
47
Use implicit object exception to determine
error to be displayed
95
2005 Pearson Education, Inc. All rights reserved.
Outline
guestBookErrorPage.jsp
(3 of 3)
Line 60
48 An exception
49
50 <%
51 } // end else
52 %>
53 <%-- end scriptlet to insert fixed template data --%>
54
55 <%-- continue error message output --%>
56 occurred while interacting with the guestbook database.
57 </p>
58 <p class = "bigRed">
59 The error message was:<br />
60 <%= exception.getMessage() %>
61 </p>
62 <p class = "bigRed">Please try again later</p>
63 </body>
64 </html>
Display the actual error message from the exception
96
2005 Pearson Education, Inc. All rights reserved.
Fig. 27.25 | JSP guest book sample output windows. (1 of 3)
97
2005 Pearson Education, Inc. All rights reserved.
Fig. 27.25 | JSP guest book sample output windows. (2 of 3)
98
2005 Pearson Education, Inc. All rights reserved.
Fig. 27.25 | JSP guest book sample output windows. (2 of 3)