Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
1
26
Web Applications:
Part 1
2007 Pearson Education, Inc. All rights reserved.
2
If any man will draw up his case, and put his
name at the foot of the first page, I will give him
an immediate reply. Where he compels me to
turn over the sheet, he must wait my leisure.
—Lord Sandwich
Rule One: Our client is always right
Rule Two: If you think our client is wrong,
see Rule One.
—Anonymous
2007 Pearson Education, Inc. All rights reserved.
3
A fair question should be
followed by a deed in silence.
—Dante Alighieri
You will come here and get books
that will open your eyes, and your ears,
and your curiosity, and turn you inside
out or outside in.
—Ralph Waldo Emerson
2007 Pearson Education, Inc. All rights reserved.
4
OBJECTIVES
In this chapter you will learn:
Web application development using Java
Technologies and Java Studio Creator 2.0.
To create JavaServer Pages with JavaServer
Faces components.
To create web applications consisting of multiple
pages.
To validate user input on a web page.
To maintain state information about a user with
session tracking and cookies.
2007 Pearson Education, Inc. All rights reserved.
5
26.1
26.2
26.3
26.4
26.5
Introduction
Simple HTTP Transactions
Multitier Application Architecture
Java Web Technologies
26.4.1 Servlets
26.4.2 JavaServer Pages
26.4.3 JavaServer Faces
26.4.4 Web Technologies in Java Studio Creator 2
Creating and Running a Simple Application in Java
Studio Creator 2
26.5.1 Examining a JSP File
26.5.2 Examining a Page Bean File
26.5.3 Event-Processing Life Cycle
26.5.4 Relationship Between the JSP and Page Bean
Files
2007 Pearson Education, Inc. All rights reserved.
6
26.6
26.7
26.8
26.9
26.5.5 Examining the XHTML Generated by a Java Web
Application
26.5.6 Building a Web Application in Java Studio
Creator 2
JSF Components
26.6.1 Text and Graphics Components
26.6.2 Validation Using Validator Components and
Custom Validators
Session Tracking
26.7.1 Cookies
26.7.2 Session Tracking with the SessionBean Object
Wrap-Up
Web Resources
2007 Pearson Education, Inc. All rights reserved.
7
26.1 Introduction
Web-based applications create web content for
web browser clients
AJAX—provides interactivity and responsiveness
users typically expect of desktop applications
1992-2007 Pearson Education, Inc. All rights reserved.
8
26.2 Simple HTTP Transactions
Hypertext Transfer Protocol (HTTP)
– set of methods and headers that allow clients and servers to
interact and exchange information
Simple web page
– Typically an XHTML document
– Contains markup that describes to a web browser how to
display the document
Hypertext data (hyperlinks)
– link to different pages or to other parts of the same page
when the user clicks the link
1992-2007 Pearson Education, Inc. All rights reserved.
9
26.2 Simple HTTP Transactions
URIs (Uniform Resource Identifiers)
– Identify data on the Internet
– Those that specify the locations of documents are called
URLs (Uniform Resource Locators)
Common URLs refer to
– Files
– Directories
– Objects that perform complex tasks
URL directs a browser to the resource (hosted on
a web server) that the user wishes to access
1992-2007 Pearson Education, Inc. All rights reserved.
10
26.2 Simple HTTP Transactions
HTTP GET method indicates that the client
wishes to obtain a resource from the server
HTTP headers provide information about the
data sent to a client, such as the MIME type
Multipurpose Internet Mail Extensions (MIME)
– Internet standard that specifies data formats so that
programs can interpret data correctly
1992-2007 Pearson Education, Inc. All rights reserved.
11
Fig. 26.1 | Client interacting with web server. Step 1: The GET request.
2007 Pearson Education, Inc. All rights reserved.
12
Fig. 26.2 | Client interacting with web server. Step 2: The HTTP response.
2007 Pearson Education, Inc. All rights reserved.
13
26.3 Multitier Application Architecture
Web-based applications are multitier (or n-tier) applications that
divide functionality into separate tiers that typically reside on
separate computers
Bottom tier
– Also called the data tier or the information tier
– Maintains the application’s data
– Typically stores data in a relational database management system
(RDBMS)
Middle tier
– Implements business logic, controller logic and presentation logic
– Acts as an intermediary between data in the information tier and the
application’s clients
– Controller logic processes client requests and retrieves data from the
database
– Presentation logic processes data from the information tier and presents
the content to the client
1992-2007 Pearson Education, Inc. All rights reserved.
14
26.3 Multitier Application Architecture
Web applications typically present data to clients as XHTML
documents.
Business logic in the middle tier
– enforces business rules
– ensures that data is reliable before the server application updates the
database or presents the data to users
Business rules dictate
– How clients can and cannot access application data
– How applications process data
Top tier
– Also called client tier
– The application’s user interface, which gathers input and displays
output
– Users interact with the application through the user interface, typically
in a web browser.
1992-2007 Pearson Education, Inc. All rights reserved.
15
26.3 Multitier Application Architecture
In response to user actions
– Client tier interacts with middle tier to make requests and
to retrieve data from information tier
– Client tier then displays data retrieved for the user
– Client tier never directly interacts with the information
tier
1992-2007 Pearson Education, Inc. All rights reserved.
16
Fig. 26.3 | Three-tier architecture.
2007 Pearson Education, Inc. All rights reserved.
17
26.4 Java Web Technologies
Continually evolve to provide developers with
higher levels of abstraction and greater
separation of the application’s tiers
Separation makes web applications more
maintainable and extensible
Java Studio Creator 2
– Drag-and-drop web-application GUI development
– Business logic placed in separate Java classes
1992-2007 Pearson Education, Inc. All rights reserved.
18
26.4.1 Servlets
Use the HTTP request-response model of
communication between client and server
Extend a server’s functionality by allowing the
server to generate dynamic content
Servlet container executes and interacts with
servlets
Packages javax.servlet and
javax.servlet.http contain the servlet
classes and interfaces.
1992-2007 Pearson Education, Inc. All rights reserved.
19
26.4.1 Servlets
Servlet container
– Receives HTTP requests from clients
– Directs each request to the appropriate servlet
– Servlet processes the request and returns response to the
client—typically an XHTML or XML document
Servlets implement the Servlet interface of
package javax.servlet
– Ensures that each servlet can execute in the framework
– Declares methods used by the servlet container to manage
the servlet’s life cycle
1992-2007 Pearson Education, Inc. All rights reserved.
20
26.4.1 Servlets
Servlet life cycle
– Begins when the servlet container loads it into memory—usually
in response to the first request for the servlet
– init method
- Called only once by container during a servlet’s life-cycle to
initialize the servlet
– service method
-
Called once per request
Receives the request
Processes it
Sends a response to the client
– destroy method
- Called to release any resources held by the servlet when container
terminates servlet
1992-2007 Pearson Education, Inc. All rights reserved.
21
26.4.2 JavaServer Pages
Extension of servlet technology
Each JSP is translated by the JSP container into
a servlet
Help separate presentation from content
Help web application programmers create
dynamic content
– By reusing predefined components
– By interacting with components using server-side
scripting
1992-2007 Pearson Education, Inc. All rights reserved.
22
26.4.2 JavaServer Pages
JavaBeans and custom tag libraries encapsulate
complex, dynamic functionality
Custom tag libraries
– Allow Java developers to hide code for database access and
other complex operations in custom tags
– Enable web-page designers who are not familiar with Java
to enhance web pages with powerful dynamic content and
processing capabilities
The JSP classes and interfaces are located in
packages javax.servlet.jsp and
javax.servlet.jsp.tagext.
1992-2007 Pearson Education, Inc. All rights reserved.
23
26.4.2 JavaServer Pages
Four key components
–
–
–
–
Directives
Actions
Scripting elements
Tag libraries
Directives
–
–
–
–
Messages to the JSP container
Specify page settings
Include content from other resources
Specify custom tag libraries for use in JSPs
Actions
– Encapsulate functionality in predefined tags
– Often are performed based on the information sent to the server as part
of a particular client request
– Can create Java objects for use in JSPs
1992-2007 Pearson Education, Inc. All rights reserved.
24
26.4.2 JavaServer Pages
Scripting elements
– Insert Java code that interacts with components in a JSP to perform
request processing
Tag libraries
– Enable programmers to create custom tags
– Enable web-page designers to manipulate JSP content without prior
Java knowledge
JavaServer Pages Standard Tag Library (JSTL)
– Provides many common web application tasks
Static content
– XHTML or XML markup
– Known as fixed-template data or fixed-template text
– Literal text is translated to a String literal in the servlet
representation of the JSP
1992-2007 Pearson Education, Inc. All rights reserved.
25
26.4.2 JavaServer Pages
First request for a JSP
– Container translates the JSP into a servlet
– Servlet handles the current and future requests to the JSP
JSPs rely on the same request/response
mechanism as servlets to process requests from
and send responses to clients
1992-2007 Pearson Education, Inc. All rights reserved.
26
Performance Tip 26.1
Some JSP containers translate JSPs into
servlets at the JSP’s deployment time
(i.e., when the application is placed on a
web server). This eliminates the translation
overhead for the first client that requests
each JSP, as the JSP will be translated
before it is ever requested by a client.
2007 Pearson Education, Inc. All rights reserved.
27
26.4.3 JavaServer Faces
Web application framework
– Simplifies the design of an application’s user interface
– Further separates a web application’s presentation
from its business logic
Framework
– Simplifies application development by providing libraries
and sometimes software tools to help you organize and
build your applications
1992-2007 Pearson Education, Inc. All rights reserved.
28
26.4.3 JavaServer Faces
JSF custom tag libraries
– Contain user interface components that simplify web-page
design
– Includes a set of APIs for handling component events
You design the look-and-feel of a page with JSF
by adding custom tags to a JSP file and
manipulating their attributes
You define the page’s behavior in a separate Java
source-code file.
1992-2007 Pearson Education, Inc. All rights reserved.
29
26.4.4 Web Technologies in Java Studio
Creator 2
Java Studio Creator 2 web applications
– Consist of one or more JSPs built in the JavaServer Faces
framework
– Each has the file-name extension .jsp and contains the web
page’s GUI elements
Java Studio Creator 2 allows you to
– Design pages visually by dragging and dropping JSF components
onto a page;
– Customize a web page by editing its .jsp file manually
Every JSP file created in Java Studio Creator 2
represents a web page and has a corresponding JavaBean
class called the page bean
1992-2007 Pearson Education, Inc. All rights reserved.
30
26.4.4 Web Technologies in Java Studio
Creator 2
JavaBean class must have
– Default (or no-argument) constructor
– get and set methods for all of its properties.
page bean
–
–
–
–
Defines properties for each of the page’s elements
Event handlers
Page life-cycle methods
Other supporting code for the web application
Every web application built with Java Studio Creator 2
has a page bean, a RequestBean, a SessionBean and
an ApplicationBean
1992-2007 Pearson Education, Inc. All rights reserved.
31
26.4.4 Web Technologies in Java Studio
Creator 2
RequestBean
– Request scope
– Exists only for the duration of an HTTP request
SessionBean
– Session scope
– Exists throughout a user’s browsing session or until the session times
out
– Unique SessionBean object for each user
ApplicationBean
–
–
–
–
–
Application scope
Shared by all instances of an application
Exists as long as the application remains deployed
Application-wide data storage or processing
One instance exists, regardless of the number of open sessions
1992-2007 Pearson Education, Inc. All rights reserved.
32
26.5 Creating and Running a Simple
Application in Java Studio Creator 2
Static Text components display text that cannot
be edited by the user
1992-2007 Pearson Education, Inc. All rights reserved.
1
<?xml version = "1.0" encoding = "UTF-8"?>
2
3
<!-- Fig. 26.4: Time.jsp -->
4
5
6
7
8
9
<!-- JSP file generated by Java Studio Creator 2 that displays -->
<!-- the current time on the web server -->
<jsp:root version = "1.2"
Time.jsp
xmlns:f = "http://java.sun.com/jsf/core"
Tag libraries available for
xmlns:h = "http://java.sun.com/jsf/html"
use in this web application (1 of 2 )
xmlns:jsp = "http://java.sun.com/JSP/Page"
10
11
xmlns:ui = "http://www.sun.com/web/ui">
<jsp:directive.page contentType = "text/html; charset = UTF-8"
12
13
14
pageEncoding = "UTF-8"/>
<f:view>
<ui:page binding = "#{Time.page}" id = "page">
15
16
17
18
19
20
<ui:html binding = "#{Time.html}" id = "html">
<ui:head binding = "#{Time.head}" id = "head"
title = "Web Time: A Simple Example">
<ui:link binding = "#{Time.link}" id = "link"
33
Outline
Configure head section of
web page
url = "/resources/stylesheet.css"/>
</ui:head>
2007 Pearson Education,
Inc. All rights reserved.
21
22
23
24
25
26
<ui:meta content = "60" httpEquiv = "refresh"/>
<ui:body binding = "#{Time.body}" id = "body"
style = "-rave-layout: grid">
<ui:form binding = "#{Time.form}" id = "form">
<ui:staticText binding = "#{Time.timeHeader}" id =
"timeHeader" style = "font-size: 18px; left: 24px;
top: 24px; position: absolute" text = "Current time
on the Web Server:"/>
27
28
<ui:staticText binding = "#{Time.clockText}" id =
"clockText" style = "background-color: black;
color: yellow; font-size: 18px; left: 24px; top:
29
30
31
32
33
34
35
34
Outline
Set up a Static
Text element
Time.jsp
(2 of 2 )
48px; position: absolute"/>
</ui:form>
</ui:body>
</ui:html>
36
</ui:page>
37
</f:view>
38 </jsp:root>
2007 Pearson Education,
Inc. All rights reserved.
35
26.5.1 Examining a JSP File
Java Studio Creator 2 generates a JSP file in response to
your interactions with the Visual Editor
All JSPs have a jsp:root element
– version attribute indicates the version of JSP being used
– One or more xmlns attributes. Each xmlns attribute
specifies a prefix and a URL for a tag library, allowing the
page to use tags specified in that library.
All JSPs generated by Java Studio Creator 2 include the
tag libraries for
–
–
–
–
JSF core components library
JSF HTML components library
JSP standard components library
JSP user interface components library
1992-2007 Pearson Education, Inc. All rights reserved.
36
26.5.1 Examining a JSP File
The jsp:directive.page element
– contentType attribute
- specifies the MIME type and the character set the page uses
– pageEncoding attribute
- specifies the character encoding used by the page source
– These attributes help the client determine how to render the content
All pages containing JSF components are represented in a component
tree with the root JSF element f:view (of type UIViewRoot)
– All JSF component elements are placed in this element
Many ui page elements have a binding attribute to bind their
values to properties in the web application’s JavaBeans
– JSF Expression Language is used to perform these bindings.
1992-2007 Pearson Education, Inc. All rights reserved.
37
26.5.1 Examining a JSP File
ui:head element
– title attribute that specifies the page’s title
ui:link element
– can be used to specify the CSS stylesheet used by a page
ui:body element
– defines the body of the page
ui:form element
– defines a form in a page.
ui:staticText component
– displays text that does not change
1992-2007 Pearson Education, Inc. All rights reserved.
38
26.5.1 Examining a JSP File
JSP elements are mapped to XHTML elements
for rendering in a browser
– Can map to different XHTML elements, depending on the
client browser and the component’s property settings
ui:staticText component
– Typically maps to an XHTML span element
– A span element contains text that is displayed on a web
page and is used to control the formatting of the text
– style attribute of ui:staticText represented as part
of the corresponding span element’s style attribute
1992-2007 Pearson Education, Inc. All rights reserved.
39
Fig. 26.5 | Sample JSF component tree.
2007 Pearson Education, Inc. All rights reserved.
40
26.5.2 Examining a Page Bean File
Page bean classes
– Inherit from class AbstractPageBean (package
com.sun.rave.web.ui.appbase
– Provides page life-cycle methods
Package com.sun.rave.web.ui.component
includes classes for many basic JSF components
A ui:staticText component is a
StaticText object (package
com.sun.rave.web.ui.component).
1992-2007 Pearson Education, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// Fig. 26.6: Time.java
// Page bean file that sets clockText to the time on the web server.
package webtime;
import
import
import
import
import
import
import
import
import
import
import
com.sun.rave.web.ui.appbase.AbstractPageBean;
com.sun.rave.web.ui.component.Body;
com.sun.rave.web.ui.component.Form;
com.sun.rave.web.ui.component.Head;
com.sun.rave.web.ui.component.Html;
com.sun.rave.web.ui.component.Link;
com.sun.rave.web.ui.component.Page;
javax.faces.FacesException;
com.sun.rave.web.ui.component.StaticText;
java.text.DateFormat;
java.util.Date;
41
Outline
Time.java
(1 of 8 )
public class Time extends AbstractPageBean
{
private int __placeholder;
// auto-generated component initialization method.
private void _init() throws Exception
{
// empty body
} // end method _init
2007 Pearson Education,
Inc. All rights reserved.
27
28
private Page page = new Page();
29
public Page getPage()
30
31
32
33
34
35
36
{
37
38
} // end method setPage
39
40
41
private Html html = new Html();
42
43
44
{
45
46
47
48
49
return page;
} // end method getPage
public void setPage( Page page )
{
this.page = page;
42
Outline
Time.java
(2 of 8 )
public Html getHtml )
return html;
} // end method getHtml
public void setHtml( Html html )
{
this.html = html;
} // end method setHtml
50
51
52
53
54
public Head getHead()
{
55
56
return head;
} // end method getHead
private Head head = new Head();
2007 Pearson Education,
Inc. All rights reserved.
57
58
public void setHead( Head head )
59
{
60
61
62
this.head = head;
} // end method setHead
63
64
65
private Link link = new Link();
66
67
{
68
} // end method getLink
43
public Link getLink()
Outline
Time.java
(3 of 8 )
return link;
69
70
71
72
public void setLink( Link link )
{
this.link = link;
73
74
75
76
77
} // end method setLink
78
{
79
80
return body;
} // end method getBody
81
82
public void setBody( Body body )
83
{
84
85
this.body = body;
} // end method setBody
private Body body = new Body();
public Body getBody()
2007 Pearson Education,
Inc. All rights reserved.
86
87
private Form form = new Form();
88
89
public Form getForm()
44
90
91
{
92
93
} // end method getForm
94
95
96
public void setForm( Form form )
{
this.form = form;
97
98
99
100
} // end method setForm
101
102
public StaticText getTimeHeader()
{
103
104
105
return timeHeader;
} // end method getStaticText1
106
public void setTimeHeader( StaticText st )
107
108
109
{
return form;
Outline
Time.java
(4 of 8 )
private StaticText timeHeader = new StaticText();
this.timeHeader = st;
} // end method setTimeHeader
110
2007 Pearson Education,
Inc. All rights reserved.
111
112
private StaticText clockText = new StaticText();
113
114
115
116
public StaticText getClockText()
{
return clockText;
} // end method getClockText
117
118
119
120
121
122
123
124
125
126
127
128
Code that was
Outline
inserted by the
designer to create a
StaticText object
45
Time.java
(5 of 8 )
public void setClockText( StaticText st )
{
this.clockText = st;
} // end method setClockText
// Construct a new page bean instance.
public Time()
{
// empty constructor
} // end constructor
2007 Pearson Education,
Inc. All rights reserved.
129
// Return a reference to the scoped data bean.
130
protected RequestBean getRequestBean()
131
{
132
133
Outline
return (RequestBean) getBean( "RequestBean" );
} // end method getRequestBean
134
135
136
137
138
// Return a reference to the scoped data bean.
protected ApplicationBean getApplicationBean()
{
return (ApplicationBean) getBean( "ApplicationBean" );
139
140
} // end method getApplicationBean
141
142
143
144
// Return a reference to the scoped data bean.
protected SessionBean getSessionBean()
{
return (SessionBean) getBean( "SessionBean" );
145
146
147
148
149
} // end method getSessionBean
150
151
152
153
154
46
Time.java
(6 of 8 )
// initializes page content
public void init()
{
super.init();
try
{
_init();
} // end try
2007 Pearson Education,
Inc. All rights reserved.
155
catch ( Exception e )
156
157
158
{
159
160
new FacesException( e );
} // end catch
log( "Time Initialization Failure", e );
throw e instanceof FacesException ? ( FacesException ) e:
161
162
} // end method init
163
164
// method called when a postback occurs.
public void preprocess()
165
{
166
167
// empty body
} // end method preprocess
47
Outline
Time.java
(7 of 8 )
2007 Pearson Education,
Inc. All rights reserved.
168
48
169
// method called before the page is rendered.
170
171
172
173
public void prerender()
{
clockText.setValue( DateFormat.getTimeInstance(
DateFormat.LONG ).format( new Date() ) );
174
175
176
177
178
} // end method prerender
// method called after rendering completes, if init was
public void destroy()
{
Outline
Programmatically
change the text in
Time.java
the StaticText
object
(8 of 8 )
called.
179
// empty body
180
} // end method destroy
181 } // end class Time
2007 Pearson Education,
Inc. All rights reserved.
49
26.5.3 Event-Processing Life Cycle
Java Studio Creator 2’s application model
– Places methods init, preprocess, prerender and destroy in
the page bean that tie into the JSF event-processing life cycle
– These represent four major stages—initialization, preprocessing,
prerendering and destruction
init method
– Called by the JSP container the first time the page is requested
and on postbacks
– Postback occurs when form data is submitted, and the page and
its contents are sent to the server to be processed
– invokes its superclass version, then tries to call the method
_init, which handles component initialization tasks
1992-2007 Pearson Education, Inc. All rights reserved.
50
26.5.3 Event-Processing Life Cycle
preprocess method
– Called after init, but only if the page is processing a
postback
prerender method
– Called just before a page is rendered by the browser
– Should be used to set component properties
destroy method
– Called after the page has been rendered, but only if the
init method was called
– Handles tasks such as freeing resources used to render the
page
1992-2007 Pearson Education, Inc. All rights reserved.
51
26.5.4 Relationship Between the JSP and
Page Bean Files
Page bean
– has a property for every element that appears in the JSP
file
1992-2007 Pearson Education, Inc. All rights reserved.
52
26.5.5 Examining the XHTML Generated
by a Java Web Application
To create a new web application
–
–
–
–
–
–
File > New Project…
Select Web in the Categories pane
Select JSF Web Application in the Projects pane
Click Next
Specify the project name and location
Click Finish to create the web application project
Single web page named Page1 created and opened by default in the
Visual Editor in Design mode when the project first loads
Design mode shows how your page renders in abrowser
The JSP file for this page, named Page1.jsp, can be viewed by
– clicking the JSP button at the top of the Visual Editor, or
– right clicking anywhere in the Visual Editor and selecting Edit JSP
Source.
1992-2007 Pearson Education, Inc. All rights reserved.
53
26.5.5 Examining the XHTML Generated
by a Java Web Application
Preview in Browser button at the top of the
Visual Editor window allows you to view your
pages in a browser without having to build and
run the application
The Refresh button redraws the page in the
Visual Editor
The Target Browser Size drop-down list allows
you to specify the optimal browser resolution for
viewing the page and allows you to see what the
page will look like in different screen resolutions
1992-2007 Pearson Education, Inc. All rights reserved.
54
26.5.5 Examining the XHTML Generated
by a Java Web Application
Projects window displays the hierarchy of all the
project’s files
– Web Pages node contains the JSP files and includes the
resources folder, which contains the project’s CSS
stylesheet and any other files the pages may need to display
properly (e.g., images)
– The Java source code, including the page bean file for each
web page and the application, session and request scope
beans, can be found under the Source Packages node
Page Navigation file
– Defines rules for navigating the project’s pages
1992-2007 Pearson Education, Inc. All rights reserved.
55
26.5.5 Examining the XHTML Generated
by a Java Web Application
Methods init, preprocess, prerender and destroy are
overridden in each page bean
– Serve as placeholders for you to customize the behavior of your web
application
Rename the JSP and Java files in your project, so that their names
are relevant to your application
–
–
–
–
Right click the JSP file in the Projects Window
Select Rename to display the Rename dialog
Enter the new file name
If Preview All Changes is checked, the Refactoring Window will
appear at the bottom of the IDE when you click Next >
– No changes will be made until you click Do Refactoring in the
Refactoring Window.
– If you do not preview the changes, refactoring occurs when you click
Next > in the Rename dialog.
1992-2007 Pearson Education, Inc. All rights reserved.
56
26.5.5 Examining the XHTML Generated
by a Java Web Application
Refactoring
– the process of modifying source code to improve its readability and
reusability without changing its behavior
– Examples: renaming methods or variables, breaking long methods into
shorter ones
– Java Studio Creator 2 has built-in refactoring tools that automate some
refactoring tasks
Title property specifies JSPs title
Components are rendered using absolute positioning
Java Studio Creator 2 is a WYSIWYG (What You See Is What You
Get) editor
Outline window displays the page bean and the request, session and
application scope beans
Clicking an item in the page bean’s component tree selects the item in
the Visual Editor
1992-2007 Pearson Education, Inc. All rights reserved.
57
26.5.5 Examining the XHTML Generated
by a Java Web Application
To build and run application
– Select Build > Build Main Project
– Select Run > Run Main Project
If changes are made to a project, the project must
be rebuilt before the changes will be reflected
when the application is viewed in a browser
F5
– build an application, then run it in debug mode
<Ctrl> F5
– Program executes without debugging enabled.
1992-2007 Pearson Education, Inc. All rights reserved.
1
2
3
4
<?xml version = "1.0"?>
<!-- Fig. 26.7: Time.html -->
<!-- The XHTML response generated when the browser requests Time.jsp. -->
5 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
6
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8
<head>
9
<meta content = "no-cache" http-equiv = "Pragma" />
10
<meta content = "no-cache" http-equiv = "Cache-Control" />
11
<meta content = "no-store" http-equiv = "Cache-Control" />
12
<meta content = "max-age=0" http-equiv = "Cache-Control" />
13
<meta content = "1" http-equiv = "Expires" />
14
15
16
17
<title>Web Time: A Simple Example</title>
<script type = "text/javascript"
src = "/WebTime/theme/com/sun/rave/web/ui/defaulttheme/
javascript/formElements.js"></script>
18
19
20
21
22
<link rel = "stylesheet" type = "text/css" href = "/WebTime/theme/
com/sun/rave/web/ui/defaulttheme/css/css_master.css" />
<link rel = "stylesheet" type = "text/css" href = "/WebTime/theme/
com/sun/rave/web/ui/defaulttheme/css/css_ie55up.css" />
<script type = "text/javascript">
23
24
25
var sjwuic_ScrollCookie = new sjwuic_ScrollCookie(
'/Time.jsp', '/WebTime/faces/Time.jsp' );
</script>
58
Outline
Time.html
(1 of 2 )
2007 Pearson Education,
Inc. All rights reserved.
26
<link id = "link" rel = "stylesheet" type = "text/css"
27
href = "/WebTime/resources/stylesheet.css" />
28
29
</head>
<meta id = "_id0" http-equiv = "refresh" content = "5" />
30
31
32
33
34
35
<body id = "body" style = "-rave-layout: grid">
<form id = "form" class = "form" method = "post"
action = "/WebTime/faces/Time.jsp"
enctype = "application/x-www-form-urlencoded">
<span id = "form:timeHeader" style = "font-size: 18px; left: 24px;
top: 24px; position: absolute">Current time on the Web Server:
36
37
38
39
40
41
</span>
<span id = "form:clockText" style = "background-color: black;
color: yellow; font-size: 18px; left: 24px; top: 48px; position:
59
Outline
Time.html
(2 of code
2 ) that
HTML
was generated for a
StaticText
object
absolute">1:18:58 AM EDT</span>
<input id = "form_hidden" name = "form_hidden"
value = "form_hidden" type = "hidden" />
42
</form>
43
</body>
44 </html>
2007 Pearson Education,
Inc. All rights reserved.
60
Fig. 26.8 | Visual Editor window in Design mode.
2007 Pearson Education, Inc. All rights reserved.
61
Fig. 26.9 | Palette in Java Studio Creator 2.
2007 Pearson Education, Inc. All rights reserved.
62
Fig. 26.10 | Projects window for the WebTime project.
2007 Pearson Education, Inc. All rights reserved.
63
Fig. 26.11 | JSP file generated for Page1 by Java Studio Creator 2.
2007 Pearson Education, Inc. All rights reserved.
64
Fig. 26.12 | Page bean file for Page1.jsp generated by Java Studio Creator 2.
2007 Pearson Education, Inc. All rights reserved.
65
Fig. 26.13 | Time.jsp after inserting the first Static Text component.
2007 Pearson Education, Inc. All rights reserved.
66
Fig. 26.14 | Time.jsp after adding the second Static Text component.
2007 Pearson Education, Inc. All rights reserved.
67
Fig. 26.15 | Outline window in Java Studio Creator 2.
2007 Pearson Education, Inc. All rights reserved.
68
Error-Prevention Tip 26.1
If you have trouble building your project
due to errors in the Java Studio Creatorgenerated XML files used for building, try
cleaning the project and building again.
You can do this by selecting Build > Clean
and Build Main Project or by pressing
<Alt> B.
2007 Pearson Education, Inc. All rights reserved.
69
26.6 JSF Components
1992-2007 Pearson Education, Inc. All rights reserved.
70
JSF Components
Description
Label
Displays text that can be associated with an input element.
Static Text
Displays text that the user cannot edit.
Text Field
Gathers user input and displays text.
Button
Triggers an event when clicked.
Hyperlink
Displays a hyperlink.
Drop Down List
Displays a drop-down list of choices.
Radio Button Group
Groups radio buttons.
Image
Displays images (e.g., GIF and JPG).
Fig. 26.16 | Commonly used JSF components.
2007 Pearson Education, Inc. All rights reserved.
71
26.6.1 Text and Graphics Components
Grid Panel component
– Designer can specify number of columns the grid should contain
– Drop components anywhere inside the panel
– They’ll automatically be repositioned into evenly spaced columns
in the order in which they are dropped
– When the number of components exceeds the number of
columns, the panel moves the additional components to a new
row
Image component
– Inserts an image into a web page
– Images must be placed in the project’s resources folder
– Use url property to specify the image to display
1992-2007 Pearson Education, Inc. All rights reserved.
72
26.6.1 Text and Graphics Components
Text Field
– Used to obtain text input from the user
Component’s JSP tags are added to the JSP file in the
order they are added to the page.
Tabbing between components navigates the components
in the order in which the JSP tags occur in the JSP file
To specify navigation order
– Drag components onto the page in appropriate order, or
– Set each input field’s Tab Index property; tab index 1 is the first
in the tab sequence
1992-2007 Pearson Education, Inc. All rights reserved.
73
26.6.1 Text and Graphics Components
Drop Down List
– displays a list from which the user can make a selection
– To configure, right click the drop-down list in Design mode and select
Configure Default Options
Hyperlink
– Adds a link to a web page
– url property specifies the linked resource
Radio Button Group
– Provides a series of radio buttons
– Edit options by right clicking the component and selecting Configure
Default Options
Button
– Triggers an action when clicked
– Typically maps to an input XHTML element with attribute type set
to submit.
1992-2007 Pearson Education, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?xml version = "1.0" encoding = "UTF-8"?>
<!-- Fig. 26.17: WebComponents.jsp -->
<!-- Registration form that demonstrates JSF components. -->
<jsp:root version = "1.2" xmlns:f = "http://java.sun.com/jsf/core"
xmlns:h = "http://java.sun.com/jsf/html" xmlns:jsp =
"http://java.sun.com/JSP/Page" xmlns:ui = "http://www.sun.com/web/ui">
<jsp:directive.page contentType = "text/html; charset = UTF-8"
pageEncoding = "UTF-8"/>
<f:view>
<ui:page binding = "#{WebComponents.page}" id = "page">
<ui:html binding = "#{WebComponents.html}" id = "html">
<ui:head binding = "#{WebComponents.head}" id = "head">
<ui:link binding = "#{WebComponents.link}" id = "link"
url = "/resources/stylesheet.css"/>
</ui:head>
<ui:body binding = "#{WebComponents.body}" id = "body"
style = "-rave-layout: grid">
<ui:form binding = "#{WebComponents.form}" id = "form">
<ui:staticText binding = "#{WebComponents.header}"
id = "header" style = "font-size: 18px; left: 24px;
top: 24px; position: absolute" text = "This is a
sample registration form."/>
<ui:staticText binding = "#{WebComponents.instructions}"
id = "instructions" style = "font-style: italic;
left: 24px; top: 72px; position: absolute" text =
"Please fill in all fields and click Register."/>
74
Outline
WebComponents
.jsp
(1 of 5 )
2007 Pearson Education,
Inc. All rights reserved.
28
29
30
31
<ui:image binding = "#{WebComponents.userImage}" id =
"userImage" style = "left: 24px; top: 120px;
position: absolute" url = "/resources/user.JPG"/>
<h:panelGrid binding = "#{WebComponents.gridPanel}"
32
33
columns = "4" id = "gridPanel" style = "height: 96px;
left: 24px; top: 168px; position: absolute"
34
35
width = "576">
<ui:image binding = "#{WebComponents.fnameImage}"
36
37
38
id = "fnameImage" url = "/resources/fname.png"/>
<ui:textField binding = "#{WebComponents.fnameTf}"
id = "fnameTf"/>
39
40
41
<ui:image binding = "#{WebComponents.lnameImage}"
id = "lnameImage" url = "/resources/lname.JPG"/>
<ui:textField binding = "#{WebComponents.lnameTF}"
42
<ui:image binding = "#{WebComponents.emailImage}"
id = "emailImage" url = "/resources/email.JPG"/>
<ui:textField binding = "#{WebComponents.emailTF}"
46
47
id = "emailTF"/>
<ui:image binding = "#{WebComponents.phoneImage}"
49
50
51
75
Designer generated
code for Grid
WebComponents
Panel
.jsp
Designer
(2 of 5 )generated
code for Text Field
id = "lnameTF"/>
43
44
45
48
Designer generated
Outline
code
for Image
id = "phoneImage" url = "/resources/phone.JPG"/>
<ui:textField binding = "#{WebComponents.phoneTF}"
id = "phoneTF" label = "Must be in the form (555)
555-5555"/>
52
</h:panelGrid>
53
54
<ui:image binding = "#{WebComponents.publicationsImage}"
id = "publicationsImage" style = "position: absolute;
55
left: 24px; top: 288px" url =
56
"/resources/publications.JPG"/>
2007 Pearson Education,
Inc. All rights reserved.
57
58
59
60
61
<ui:staticText binding =
"#{WebComponents.publicationLabel}" id =
"publicationLabel" style = "left: 240px; top: 288px;
position: absolute" text = "Which book would you like
information about?"/>
62
63
64
<ui:dropDown binding = "#{WebComponents.booksDropDown}"
id = "bookcDropDown" items = "#{WebComponents.
booksDropDownDefaultOptions.options}" style = "left:
65
66
67
24px; top: 336px; position: absolute; width: 240px"/>
<ui:hyperlink binding = "#{WebComponents.deitelLink}"
id = "deitelLink" style = "left: 24px; top: 384px;
68
position: absolute" target = "_blank" text = "Click
69
70
71
"osImage" style = "position: absolute; left: 24px;
73
top: 432px" url = "/resources/os.JPG"/>
77
Outline
Designer
generated
WebComponents
code
for Drop
.jsp
Down List
(3 of 5 )
Designer generated
code for Hyperlink
here for more information about our books."
url = "http://www.deitel.com"/>
<ui:image binding = "#{WebComponents.osImage}" id =
72
74
75
76
76
<ui:staticText binding = "#{WebComponents.osLabel}" id =
"osLabel" style = "left: 240px; top: 432px; position:
absolute" text = "Which operating system are you
using?"/>
2007 Pearson Education,
Inc. All rights reserved.
78
79
<ui:radioButtonGroup binding =
"#{WebComponents.osRadioButtonGroup}" id =
"osRadioButtonGroup" items = "#{WebComponents.
80
81
82
83
84
85
86
87
osRadioButtonGroupDefaultOptions.options}" style =
"left: 24px; top: 504px; position: absolute"/>
<ui:button binding = "#{WebComponents.registerButton}"
id = "registerButton" style = "left: 23px; top:
648px; position: absolute" text = "Register"/>
</ui:form>
</ui:body>
Designer generated
Outline
code
for Radio
Button Group
77
Designer
generated
WebComponents
code
for Button
.jsp
(4 of 5 )
88
</ui:html>
89
</ui:page>
90
</f:view>
91 </jsp:root>
2007 Pearson Education,
Inc. All rights reserved.
78
Outline
WebComponents
.jsp
(5 of 5 )
2007 Pearson Education,
Inc. All rights reserved.
79
26.6.2 Validation Using Validator
Components and Custom Validators
Validation
– Helps prevent processing errors due to incomplete or improperly
formatted user input.
Length Validator
– Determines whether a field contains an acceptable number of
characters
Double Range Validators and Long Range Validators
– Determine whether numeric input falls within acceptable ranges
Package javax.faces.validators contains the
validator classes
1992-2007 Pearson Education, Inc. All rights reserved.
80
26.6.2 Validation Using Validator
Components and Custom Validators
Label component
– Describes another component
– Can be associated with a user input field by setting its for
property
Message component
– Displays an error message when validation fails
To associate a Label or Message component
with another component, hold the Ctrl and Shift
keys, then drag the Label or Message to the
appropriate component
1992-2007 Pearson Education, Inc. All rights reserved.
81
26.6.2 Validation Using Validator
Components and Custom Validators
Set the required property of a component to
ensure that the user enters data for it.
An input field’s required property must be set
to true for validation to occur
In the Visual Editor the label for a required field
is automatically marked by a red asterisk.
If a user submits a form with a missing required
field, the default error message for that field will
be displayed in its associated ui:message
component
1992-2007 Pearson Education, Inc. All rights reserved.
82
26.6.2 Validation Using Validator
Components and Custom Validators
To edit a Double Range Validator’s or a Long
Range Validator’s properties
– Click its node in the Outline window in Design mode
– Set the maximum and minimum properties in the
Properties window
Can limit user input length using validation
– Set a Text Field’s maxLength property
1992-2007 Pearson Education, Inc. All rights reserved.
83
26.6.2 Validation Using Validator
Components and Custom Validators
To ensure properly formatted input
– Can match input against a regular expression
No built in regular expression, but you can add
your own custom validator methods to the page
bean file
Add a custom validator method
– Right click the appropriate input component
– Select Edit Event Handler > validate to create a
validation method in the page bean file
1992-2007 Pearson Education, Inc. All rights reserved.
1
<?xml version = "1.0" encoding = "UTF-8"?>
2
3
<!-- Fig. 26.18: Validation.jsp -->
4
5
<!-- JSP that demonstrates validation of user input. -->
<jsp:root version = "1.2" xmlns:f = "http://java.sun.com/jsf/core"
6
7
8
9
xmlns:h = "http://java.sun.com/jsf/html" xmlns:jsp =
"http://java.sun.com/JSP/Page" xmlns:ui = "http://www.sun.com/web/ui">
<jsp:directive.page contentType = "text/html; charset = UTF-8"
pageEncoding = "UTF-8"/>
10
11
<f:view>
<ui:page binding = "#{Validation.page}" id = "page">
12
13
14
15
18
<ui:body binding = "#{Validation.body}" focus = "form1:nameTF"
23
24
25
26
Validation.jsp
(1 of 6 )
title = "Validation">
<ui:link binding = "#{Validation.link}" id = "link"
url = "/resources/stylesheet.css"/>
</ui:head>
21
22
Outline
<ui:html binding = "#{Validation.html}" id = "html">
<ui:head binding = "#{Validation.head}" id = "head"
16
17
19
20
84
id = "body" style = "-rave-layout: grid">
<ui:form binding = "#{Validation.form}" id = "form">
<ui:staticText binding = "#{Validation.header}" id =
"header" style = "font-size: 16px; height: 22px;
left: 24px; top: 24px; position: absolute; width:
456px" text = "Please fill out the following form."/>
<ui:staticText binding = "#{Validation.instructions}"
id = "instructions" style = "font-size: 14px;
27
28
font-style: italic; left: 24px; top: 48px; position:
absolute; width: 406px" text = "All fields are
29
required and must contain valid information."/>
2007 Pearson Education,
Inc. All rights reserved.
30
<ui:textField binding = "#{Validation.nameTF}" columns =
31
"30" id = "nameTF" required = "true" style = "left:
32
33
168px; top: 96px; position: absolute; width: 216px"
validator =
34
35
36
37
38
39
40
"#{Validation.nameLengthValidator.validate}"/>
<ui:textField binding = "#{Validation.emailTF}"
columns = "28" id = "emailTF" required = "true"
style = "left: 168px; top: 144px; position: absolute;
width: 216px" validator =
"#{Validation.emailTF_validate}"/>
<ui:textField binding = "#{Validation.phoneTF}"
41
42
43
columns = "30" id = "phoneTF" required = "true"
style = "left: 168px; top: 192px; position: absolute;
width: 216px" validator =
44
"#{Validation.phoneTF_validate}"/>
45
46
47
<ui:label binding = "#{Validation.nameLabel}" for =
"nameTF" id = "nameLabel" style = "font-weight:
normal; height: 24px; left: 24px; top: 96px;
48
49
position: absolute; width: 94px" text = "Name:"/>
<ui:label binding = "#{Validation.emailLabel}" for =
50
"emailTF" id = "emailLabel" style = "font-weight:
51
52
53
normal; height: 24px; left: 24px; top: 144px;
position: absolute; width: 142px" text =
"Email Address:"/>
54
<ui:label binding = "#{Validation.phoneLabel}" for =
55
56
"phoneTF" id = "phoneLabel" style = "font-weight:
normal; height: 24px; left: 24px; top: 192px;
57
position: absolute; width: 142px" text =
58
"Phone number:"/>
85
Outline
Specifies the
validator for the
Validation.jsp
name Text
Field
(2 of
Specifies
the6 )
validator for the
email Text Field
Specifies the
validator for the
phone number
Text Field
2007 Pearson Education,
Inc. All rights reserved.
59
60
61
62
63
64
65
66
67
68
69
70
<ui:button action = "#{Validation.submitButton_action}"
binding = "#{Validation.submitButton}" id =
"submitButton" style = "left: 23px; top: 240px;
position: absolute; width: 72px" text = "Submit"/>
<ui:message binding = "#{Validation.emailMessage}" for =
"emailTF" id = "emailMessage" showDetail = "false"
showSummary = "true" style = "left: 408px; top:
144px; position: absolute"/>
<ui:message binding = "#{Validation.phoneMessage}" for =
"phoneTF" id = "phoneMessage" showDetail = "false"
<ui:message binding = "#{Validation.nameMessage}" for =
"nameTF" id = "nameMessage" showDetail = "false"
showSummary = "true" style = "left: 408px; top: 96px;
74
75
76
position: absolute"/>
<ui:staticText binding = "#{Validation.resultText}"
escape = "false" id = "resultText" rendered = "false"
77
78
79
80
81
style = "height: 46px; left: 24px; top: 288px;
position: absolute; width: 312px" text = "Thank you
for your submission.
<br/>We received the
following information:"/>
<h:panelGrid bgcolor = "seashell" binding =
87
88
Outline
Validation.jsp
(3 of 6 )
showSummary = "true" style = "left: 408px; top:
192px; position: absolute"/>
71
72
73
82
83
84
85
86
86
"#{Validation.gridPanel}" columns = "2" id =
"gridPanel" rendered = "false" style = "height: 96px;
left: 24px; top: 336px; position: absolute"
width = "312">
<ui:staticText binding =
"#{Validation.nameResultLabel}" id =
"nameResultLabel" text = "Name:"/>
2007 Pearson Education,
Inc. All rights reserved.
89
90
<ui:staticText binding = "#{Validation.nameResult}"
id = "nameResult"/>
91
<ui:staticText binding =
"emailResultLabel" text = "E-mail address:"/>
<ui:staticText binding = "#{Validation.emailResult}"
id = "emailResult"/>
<ui:staticText binding =
"#{Validation.phoneResultLabel}" id =
93
94
95
96
97
Validation.jsp
(4 of 6 )
"phoneResultLabel" text ="Phone number:"/>
98
<ui:staticText binding = "#{Validation.phoneResult}"
id = "phoneResult"/>
99
100
</h:panelGrid>
</ui:form>
101
102
106
Outline
"#{Validation.emailResultLabel}" id =
92
103
104
105
87
</ui:body>
</ui:html>
</ui:page>
</f:view>
107 </jsp:root>
2007 Pearson Education,
Inc. All rights reserved.
88
Outline
Validation.jsp
(5 of 6 )
2007 Pearson Education,
Inc. All rights reserved.
89
Outline
Validation.jsp
(6 of 6 )
2007 Pearson Education,
Inc. All rights reserved.
90
26.7 Session Tracking
Personalization
– Makes it possible for e-businesses to communicate
effectively with their customers
– Improves the user’s ability to locate desired products and
services
Privacy
– Some consumers embrace the idea of tailored content
– Others fear the possible adverse consequences if the
information they provide to e-businesses is released or
collected by tracking technologies
1992-2007 Pearson Education, Inc. All rights reserved.
91
26.7 Session Tracking
To provide personalized services, must be able to
recognize clients
HTTP is a stateless protocol
– It does not support persistent connections that would
enable web servers to maintain state information
regarding particular clients
To help the server distinguish among clients, each
client must identify itself to the server
Tracking individual clients
– Cookies
– SessionBean object
1992-2007 Pearson Education, Inc. All rights reserved.
92
26.7 Session Tracking
Other tracking methods
– "hidden" form elements
- A web form can write session-tracking data into a form
- When the user submits the form, all the form data, including
the "hidden" fields, is sent to the form handler on the web
server
– URL rewriting
- Web server embeds session-tracking information directly in
the URLs of hyperlinks that the user clicks to send
subsequent requests
1992-2007 Pearson Education, Inc. All rights reserved.
93
26.7.1 Cookies
Cookie
– A piece of data typically stored in a text file on the user’s
computer
– Maintains information about the client during and
between browser sessions
When a user visits the website, the user’s computer might
receive a cookie
– This cookie is then reactivated each time the user revisits
that site
HTTP-based interactions between a client and a server
– Includes a header containing information either about the
request (when the communication is from the client to the
server) or about the response (when the communication is
from the server to the client)
1992-2007 Pearson Education, Inc. All rights reserved.
94
26.7.1 Cookies
In a request, the header includes
– Request type
– Any cookies that have been sent previously from the server to be
stored on the client machine
In a response, the header includes
– Any cookies the server wants to store on the client computer
– Other information, such as the MIME type of the response
Expiration date determines how long the cookie remains
on the client’s computer
– If not set, the web browser maintains the cookie for the browsing
session’s duration
1992-2007 Pearson Education, Inc. All rights reserved.
95
26.7.1 Cookies
Setting the action handler for a Hyperlink
enables you to respond to a click without
redirecting the user to another page
To add an action handler to a Hyperlink that
should also direct the user to another page
– Add a rule to the Page Navigation file
– Right click in the Visual Designer and select Page
Navigation…, then drag the appropriate Hyperlink to the
destination page
1992-2007 Pearson Education, Inc. All rights reserved.
96
26.7.1 Cookies
A cookie object is an instance of class Cookie in package
javax.servlet.http
An HttpServletResponse (from package
javax.servlet.http) represents the response
– This object can be accessed by invoking the method
getExternalContext on the page bean, then invoking
getResponse on the resulting object
An HttpServletRequest (from package
javax.servlet.http) represents the request
– This object can be obtained by invoking method
getExternalContext on the page bean, then invoking
getRequest on the resulting object.
HttpServletRequest method getCookies returns an array of
the cookies previously written to the client.
Web server cannot access cookies created by servers in other domains
1992-2007 Pearson Education, Inc. All rights reserved.
1
// Fig. 26.19: Validation.java
2
// Page bean for validating user input and redisplaying that input if
3
// valid.
4
5
package validation;
6
import com.sun.rave.web.ui.appbase.AbstractPageBean;
7
8
9
10
import
import
import
import
com.sun.rave.web.ui.component.Body;
com.sun.rave.web.ui.component.Form;
com.sun.rave.web.ui.component.Head;
com.sun.rave.web.ui.component.Html;
11
12
13
14
import
import
import
import
com.sun.rave.web.ui.component.Link;
com.sun.rave.web.ui.component.Page;
javax.faces.FacesException;
com.sun.rave.web.ui.component.StaticText;
97
Outline
Validation.java
(1 of 5 )
15 import com.sun.rave.web.ui.component.TextField;
16 import com.sun.rave.web.ui.component.TextArea;
17 import com.sun.rave.web.ui.component.Label;
18 import com.sun.rave.web.ui.component.Button;
19 import com.sun.rave.web.ui.component.Message;
20 import javax.faces.component.UIComponent;
21 import javax.faces.context.FacesContext;
22
23
24
25
import
import
import
import
javax.faces.validator.ValidatorException;
javax.faces.application.FacesMessage;
javax.faces.component.html.HtmlPanelGrid;
javax.faces.validator.LengthValidator;
2007 Pearson Education,
Inc. All rights reserved.
26
98
27 public class Validation extends AbstractPageBean
28 {
29
Outline
private int __placeholder;
30
31
32
33
34
private void _init() throws Exception
{
nameLengthValidator.setMaximum( 30 );
} // end method _init
Validation.java
(2 of 5 )
35
36
// To save space, we omitted the code in lines 36-345. The complete
37
38
// source code is provided with this chapter's examples.
346
347
348
349
public Validation()
{
// empty constructor
} // end constructor
350
351
352
353
354
355
356
357
358
359
protected RequestBean getRequestBean()
{
return (RequestBean) getBean( "RequestBean" );
} // end method getRequestBean
protected ApplicationBean getApplicationBean()
{
return (ApplicationBean) getBean( "ApplicationBean" );
} // end method getApplicationBean
360
2007 Pearson Education,
Inc. All rights reserved.
361
362
363
364
365
366
367
368
369
370
protected SessionBean getSessionBean()
{
return (SessionBean) getBean( "SessionBean" );
99
Outline
} // end method getSessionBean
public void init()
{
super.init();
try
{
371
372
_init();
} // end try
373
374
375
catch ( Exception e )
{
log( "Validation Initialization Failure", e );
376
377
378
throw e instanceof FacesException ? (FacesException) e:
new FacesException( e );
} // end catch
379
380
381
382
383
} // end method init
384
385
386
387
388
} // end method preprocess
389
390
} // end method prerender
Validation.java
(3 of 5 )
public void preprocess()
{
// empty body
public void prerender()
{
// empty body
2007 Pearson Education,
Inc. All rights reserved.
391
392
public void destroy()
{
393
394
// empty body
} // end method destroy
100
Outline
395
396
397
398
399
400
401
// validates entered email address against the regular expression
// that represents the form of a valid email address.
public void emailTF_validate( FacesContext context,
UIComponent component, Object value )
{
String email = String.valueOf( value );
402
403
404
// if entered email address is not in a valid format
if ( !email.matches(
"\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*" ) )
405
406
{
throw new ValidatorException( new FacesMessage(
407
408
409
410
411
"Enter a valid email address, e.g. [email protected]" ) );
} // end if
} // end method emailTF_validate
412
413
414
// validates entered email address against the regular expression
// that represents the form of a valid email address.
public void phoneTF_validate( FacesContext context,
415
416
Validation.java
(4 of 5 )
Custom email
validation via
regular expression
UIComponent component, Object value )
{
417
String phone = String.valueOf( value );
418
419
// if entered phone number is not in a valid format
2007 Pearson Education,
Inc. All rights reserved.
420
421
if ( !phone.matches(
"((\\(\\d{3}\\) ?)|(\\d{3}-))?\\d{3}-\\d{4}" ) )
422
{
423
424
425
426
427
428
throw new ValidatorException( new FacesMessage(
"Enter a valid phone number, e.g. (555) 555-1234" ) );
} // end if
} // end method phoneTF_validate
429
430
431
432
433
434
public String submitButton_action()
{
String name = String.valueOf( nameTF.getValue() );
String email = String.valueOf( emailTF.getValue() );
String phone = String.valueOf( phoneTF.getValue() );
nameResult.setValue( name );
// displays validated form entries in a Grid Panel.
435
436
emailResult.setValue( email );
phoneResult.setValue( phone );
437
438
439
440
gridPanel.setRendered( true );
resultText.setRendered( true );
return null;
} // end method submitButton_action
101
Custom phone
Outline
number validation
via regular
expression
Validation.java
(5 of 5 )
441 } // end class Validation
2007 Pearson Education,
Inc. All rights reserved.
102
Portability Tip 26.1
Clients may disable cookies in their web
browsers for more privacy. When such
clients use web applications that depend
on cookies to maintain state information,
the applications will not execute correctly.
2007 Pearson Education, Inc. All rights reserved.
1
<?xml version = "1.0" encoding = "UTF-8"?>
2
3
<!-- Fig. 26.20: Options.jsp -->
4
5
<!-- JSP file that allows the user to select a programming language. -->
<jsp:root version = "1.2" xmlns:f = "http://java.sun.com/jsf/core"
6
7
8
9
xmlns:h = "http://java.sun.com/jsf/html" xmlns:jsp =
"http://java.sun.com/JSP/Page" xmlns:ui = "http://www.sun.com/web/ui">
<jsp:directive.page contentType = "text/html; charset = UTF-8"
pageEncoding = "UTF-8"/>
10
11
<f:view>
<ui:page binding = "#{Options.page}" id = "page">
12
13
14
15
Options.jsp
(1 of 4 )
"Options">
<ui:link binding = "#{Options.link}" id = "link"
url = "/resources/stylesheet.css"/>
</ui:head>
18
<ui:body binding = "#{Options.body}" id = "body"
21
22
Outline
<ui:html binding = "#{Options.html}" id = "html">
<ui:head binding = "#{Options.head}" id = "head" title =
16
17
19
20
103
style = "-rave-layout: grid">
<ui:form binding = "#{Options.form}" id = "form">
<ui:label binding = "#{Options.languageLabel}" for =
"languageList" id = "languageLabel" style =
23
24
"font-size: 16px; font-weight: bold; left: 24px; top:
24px; position: absolute" text = "Select a
25
26
programming language:"/>
<ui:radioButtonGroup binding = "#{Options.languageList}"
27
28
id = "languageList" items =
"#{Options.languageListOptions.options}" style =
29
"left: 24px; top: 48px; position: absolute"/>
2007 Pearson Education,
Inc. All rights reserved.
30
31
<ui:staticText binding = "#{Options.responseLabel}" id =
"responseLabel" rendered = "false" style =
32
33
"font-size: 16px; font-weight: bold; height: 24px;
left: 24px; top: 24px; position: absolute;
34
35
width: 216px"/>
<ui:hyperlink action = "#{Options.languagesLink_action}"
36
37
binding = "#{Options.languagesLink}" id =
"languagesLink" rendered = "false" style = "left:
24px; top: 96px; position: absolute" text = "Click
here to choose another language."/>
<ui:hyperlink action =
38
39
40
41
42
"#{Options.recommendationsLink_action}" binding =
"#{Options.recommendationsLink}" id =
43
44
45
46
"recommendationsLink" rendered = "false" style =
"left: 24px; top: 120px; position: absolute" text =
"Click here to get book recommendations." url =
"/faces/Recommendations.jsp"/>
47
<ui:button action = "#{Options.submit_action}" binding =
Outline
Options.jsp
(2 of 4 )
"#{Options.submit}" id = "submit" style = "left:
23px; top: 192px; position: absolute" text =
48
49
"Submit"/>
</ui:form>
</ui:body>
50
51
52
53
54
55
104
</ui:html>
</ui:page>
</f:view>
56 </jsp:root>
2007 Pearson Education,
Inc. All rights reserved.
105
Outline
Options.jsp
(3 of 4 )
2007 Pearson Education,
Inc. All rights reserved.
106
Outline
Options.jsp
(4 of 4 )
2007 Pearson Education,
Inc. All rights reserved.
107
Fig. 26.21 | Editing the Page Navigation file.
2007 Pearson Education, Inc. All rights reserved.
1
2
// Fig. 26.22: Options.java
// Page bean that stores the user’s language selection as a cookie on the
3
4
// client.
package cookies;
108
Outline
5
6
7
8
9
10
11
import
import
import
import
import
import
com.sun.rave.web.ui.appbase.AbstractPageBean;
com.sun.rave.web.ui.component.Body;
com.sun.rave.web.ui.component.Form;
com.sun.rave.web.ui.component.Head;
com.sun.rave.web.ui.component.Html;
com.sun.rave.web.ui.component.Link;
Options.java
(1 of 6 )
12 import com.sun.rave.web.ui.component.Page;
13 import javax.faces.FacesException;
14 import com.sun.rave.web.ui.component.StaticText;
15 import com.sun.rave.web.ui.component.Label;
16 import com.sun.rave.web.ui.component.RadioButtonGroup;
17
18
19
20
import
import
import
import
com.sun.rave.web.ui.model.SingleSelectOptionsList;
com.sun.rave.web.ui.component.Hyperlink;
com.sun.rave.web.ui.component.Button;
javax.servlet.http.HttpServletResponse;
21
22
23
24
25
import javax.servlet.http.Cookie;
import java.util.Properties;
26
27
private int __placeholder;
public class Options extends AbstractPageBean
{
2007 Pearson Education,
Inc. All rights reserved.
28
29
// method _init initializes components and sets the
// options for the radio button group.
30
31
32
private void _init() throws Exception
{
languageListOptions.setOptions(
new com.sun.rave.web.ui.model.Option[]
{
new com.sun.rave.web.ui.model.Option( "Java", "Java" ),
33
34
35
new com.sun.rave.web.ui.model.Option( "C", "C" ),
new com.sun.rave.web.ui.model.Option( "C++", "C++" ),
new com.sun.rave.web.ui.model.Option( "Visual/Basic/2005",
36
37
38
Outline
Options.java
(2 of 6 )
"Visual Basic 2005" ),
39
new com.sun.rave.web.ui.model.Option( "Visual/C#/2005",
"Visual C# 2005" )
40
41
42
43
109
}
);
44
} // end method _init
45
46
47
// To save space, we omitted the code in lines 46-203. The complete
// source code is provided with this chapter's examples.
48
2007 Pearson Education,
Inc. All rights reserved.
204
private Properties books = new Properties();
205
206
// Construct a new page bean instance and initialize the properties
207
208
// that map languages to ISBN numbers of recommended books.
public Options()
209
{
210
211
212
// initialze the Properties object of values to be stored as
// cookies.
books.setProperty( "Java", "0-13-222220-5" );
213
books.setProperty( "C", "0-13-142644-3" );
214
215
books.setProperty( "C++", "0-13-185757-6" );
books.setProperty( "Visual/Basic/2005", "0-13-186900-0" );
216
books.setProperty( "Visual/C#/2005", "0-13-152523-9" );
217
} // end Options constructor
218
219
protected ApplicationBean getApplicationBean()
220
221
222
223
224
225
226
227
228
229
230
{
231
232
233
return (SessionBean) getBean( "SessionBean" );
} // end method getSessionBean
110
Outline
Options.java
(3 of 6 )
return (ApplicationBean) getBean( "ApplicationBean" );
} // end method getApplicationBean
protected RequestBean getRequestBean()
{
return (RequestBean) getBean( "RequestBean" );
} // end method getRequestBean
protected SessionBean getSessionBean()
{
2007 Pearson Education,
Inc. All rights reserved.
234
public void init()
235
{
236
super.init();
237
238
try
{
_init();
239
} // end try
catch ( Exception e )
{
240
241
242
243
log( "Options Initialization Failure", e );
244
245
throw e instanceof FacesException ? ( FacesException ) e:
new FacesException( e );
246
} // end catch
247
} // end method init
248
249
public void preprocess()
250
251
252
253
254
255
256
257
258
259
260
{
261
262
263
// empty body
} // end method destroy
111
Outline
Options.java
(4 of 6 )
// empty body
} // end method preprocess
public void prerender()
{
// empty body
} // end method prerender
public void destroy()
{
2007 Pearson Education,
Inc. All rights reserved.
264
265
// Action handler for the Submit button. Checks to see if a language
// was selected and if so, registers a cookie for that language and
266
267
// sets the responseLabel to indicate the chosen language.
public String submit_action()
268
269
270
271
{
String msg = "Welcome to Cookies!
You ";
if ( languageList.getSelected() != null )
273
274
275
276
{
Outline
Options.java
// if the user made a selection
272
112
(5 of 6 )
String language = languageList.getSelected().toString();
String displayLanguage = language.replace( '/', ' ' );
msg += "selected " + displayLanguage + ".";
277
278
279
280
281
// get ISBN number of book for the given language.
String ISBN = books.getProperty( language );
282
283
284
Cookie cookie = new Cookie( language, ISBN );
// add cookie to the response header to place it on the user's
285
286
// machine
HttpServletResponse response =
287
288
(HttpServletResponse) getExternalContext().getResponse();
response.addCookie( cookie );
289
// create cookie using language-ISBN name-value pair
} // end if
Creates the
Cookie object
Gets the response
object and adds the
Cookie to the
response
2007 Pearson Education,
Inc. All rights reserved.
else
290
msg += "did not select a language.";
291
292
293
responseLabel.setValue( msg );
294
languageList.setRendered( false );
295
languageLabel.setRendered( false );
296
297
298
299
submit.setRendered( false );
responseLabel.setRendered( true );
languagesLink.setRendered( true );
recommendationsLink.setRendered( true );
300
301
return null; // reloads the page
} // end method submit_action
302
303
304
305
// redisplay the components used to allow the user to select a
// language.
public String languagesLink_action()
306
307
308
309
310
113
Outline
Options.java
(6 of 6 )
{
responseLabel.setRendered( false );
languagesLink.setRendered( false );
recommendationsLink.setRendered( false );
languageList.setRendered( true );
311
languageLabel.setRendered( true );
312
submit.setRendered( true );
313
return null;
314
} // end method languagesLink_action
315 } // end class Options
2007 Pearson Education,
Inc. All rights reserved.
114
Software Engineering Observation 26.1
Java Studio Creator 2 can automatically
import any missing packages your Java file
needs. For example, after adding the
Properties object to Options.java,
you can right click in the Java editor window
and select Fix Imports to automatically
import java.util.Properties.
2007 Pearson Education, Inc. All rights reserved.
1
2
<?xml version = "1.0" encoding = "UTF-8"?>
3
<!-- Fig. 26.23: Recommendations.jsp -->
4
5
6
<!-- JSP file that displays book recommendations based on cookies. -->
<jsp:root version = "1.2" xmlns:f = "http://java.sun.com/jsf/core"
xmlns:h = "http://java.sun.com/jsf/html" xmlns:jsp =
7
8
9
"http://java.sun.com/JSP/Page" xmlns:ui = "http://www.sun.com/web/ui">
<jsp:directive.page contentType = "text/html; charset = UTF-8"
pageEncoding = "UTF-8"/>
10
11
<f:view>
<ui:page binding = "#{Recommendations.page}" id = "page">
12
13
14
15
16
17
18
19
20
21
115
Outline
Recommendations
.jsp
(1 of 2 )
<ui:html binding = "#{Recommendations.html}" id = "html">
<ui:head binding = "#{Recommendations.head}" id = "head"
title = "Recommendations">
<ui:link binding = "#{Recommendations.link}" id = "link"
url = "/resources/stylesheet.css"/>
</ui:head>
<ui:body binding = "#{Recommendations.body}" id = "body"
style = "-rave-layout: grid">
<ui:form binding = "#{Recommendations.form}" id = "form">
<ui:label binding = "#{Recommendations.languageLabel}"
22
for = "booksListBox" id = "languageLabel" style =
23
24
"font-size: 20px; font-weight: bold; left: 24px; top:
24px; position: absolute" text = "Recommendations"/>
25
26
<ui:listbox binding = "#{Recommendations.booksListBox}"
id = "booksListBox" items = "#{Recommendations.
27
booksListBoxOptions.options}" rows = "6" style =
28
29
"left: 24px; top: 72px; position: absolute;
width: 360px"/>
2007 Pearson Education,
Inc. All rights reserved.
<ui:hyperlink action = "case1" binding =
"#{Recommendations.optionsLink}" id = "optionsLink"
30
31
style = "left: 24px; top: 192px; position: absolute"
text = "Click here to choose another language."/>
32
33
</ui:form>
</ui:body>
34
35
36
37
</ui:html>
</ui:page>
38
</f:view>
39 </jsp:root>
116
Outline
Recommendations
.jsp
(2 of 2 )
2007 Pearson Education,
Inc. All rights reserved.
1
// Fig. 26.24: Recommendations.java
2
3
// Page bean that displays book recommendations based on cookies storing
// user’s selected programming languages.
4
package cookies;
5
6
import com.sun.rave.web.ui.appbase.AbstractPageBean;
7
8
import com.sun.rave.web.ui.component.Body;
import com.sun.rave.web.ui.component.Form;
9
import com.sun.rave.web.ui.component.Head;
10 import com.sun.rave.web.ui.component.Html;
117
Outline
Recommendations
.java
(1 of 4 )
11 import com.sun.rave.web.ui.component.Link;
12 import com.sun.rave.web.ui.component.Page;
13 import javax.faces.FacesException;
14 import com.sun.rave.web.ui.component.Listbox;
15
16
17
18
import
import
import
import
com.sun.rave.web.ui.model.DefaultOptionsList;
com.sun.rave.web.ui.component.Label;
com.sun.rave.web.ui.component.Hyperlink;
com.sun.rave.web.ui.model.Option;
19 import javax.servlet.http.HttpServletRequest;
20 import javax.servlet.http.Cookie;
21 import com.sun.rave.web.ui.component.HiddenField;
22
23 public class Recommendations extends AbstractPageBean
24 {
25
private int __placeholder;
26
27
private void _init() throws Exception
28
{
29
// empty body
30
} // end method _init()
2007 Pearson Education,
Inc. All rights reserved.
31
32
33
118
// To save space, we omitted the code in lines 32-151. The complete
// source code is provided with this chapter's examples.
Outline
34
152
153
public Recommendations()
{
154
155
// empty body
} // end constructor
156
157
158
159
160
161
protected RequestBean getRequestBean()
{
return (RequestBean) getBean( "RequestBean" );
} // end method getRequestBean
162
163
protected ApplicationBean getApplicationBean()
{
164
165
166
167
168
return (ApplicationBean) getBean( "ApplicationBean" );
} // end method getApplicationBean
169
170
171
Recommendations
.java
(2 of 4 )
protected SessionBean getSessionBean()
{
return (SessionBean) getBean( "SessionBean" );
} // end method getSessionBean
2007 Pearson Education,
Inc. All rights reserved.
172
173
174
public void init()
{
super.init();
175
176
try
{
177
178
179
_init();
} // end try
catch ( Exception e )
180
181
{
log( "Recommendations Initialization Failure", e );
119
Outline
Recommendations
.java
(3 of 4 )
throw e instanceof FacesException ? (FacesException) e:
new FacesException( e );
182
183
184
185
} // end catch
} // end method init
186
187
188
public void preprocess()
{
189
190
191
192
// empty body
} // end method preprocess
193
{
public void prerender()
194
195
//retrieve client's cookies
HttpServletRequest request =
196
197
198
(HttpServletRequest)getExternalContext().getRequest();
Cookie [] cookies = request.getCookies();
199
200
201
// if there are cookies, store the corresponding books and ISBN
// numbers in an array of Options
Option [] recommendations;
Obtains the
Cookie object(s)
from the request
2007 Pearson Education,
Inc. All rights reserved.
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
120
if ( cookies.length > 1 )
{
recommendations = new Option[ cookies.length - 1 ];
for ( int i = 0; i < cookies.length - 1; i++ )
{
String language =
cookies[ i ].getName().replace( ’/’, ’ ’ );
recommendations[ i ] = new Option( language + " How to "
"Program. ISBN#: " + cookies[ i ].getValue() );
} // end for
} // end if
Outline
Recommendations
.java
(4 of 4 )
// otherwise store a message indicating no language was selected
else
{
recommendations = new Option[ 1 ];
recommendations[ 0 ] = new Option( "No recommendations. " +
"Please select a language." ) ;
} // end else
booksListBox.setItems( recommendations );
} // end method prerender
public void destroy()
{
// empty body
} // end method destroy
230 } // end class Recommendations
2007 Pearson Education,
Inc. All rights reserved.
121
Methods
Description
getDomain
Returns a String containing the cookie’s domain (i.e., the domain from
which the cookie was written). This determines which web servers can
receive the cookie. By default, cookies are sent to the web server that
originally sent the cookie to the client. Changing the Domain property
causes the cookie to be returned to a web server other than the one that
originally wrote it.
getMaxAge
Returns an int indicating how many seconds the cookie will persist on the
browser. This is –1 by default, meaning the cookie will persist until the
browser is shut down.
getName
Returns a String containing the cookie’s name.
getPath
Returns a String containing the path to a directory on the server to which
the cookie applies. Cookies can be “targeted” to specific directories on the
web server. By default, a cookie is returned only to applications operating in
the same directory as the application that sent the cookie or a subdirectory
of that directory. Changing the Path property causes the cookie to be
returned to a directory other than the one from which it was originally
written.
getSecure
Returns a bool value indicating whether the cookie should be transmitted
through a secure protocol. The value true causes a secure protocol to be
used.
getValue
Returns a String containing the cookie’s value.
Fig. 26.25 | javax.servlet.http.Cookie methods.
2007 Pearson Education, Inc. All rights reserved.
122
26.7.2 Session Tracking with the
SessionBean Object
Can perform session tracking with class SessionBean that is
provided in each web application created with Java Studio Creator 2
– When a new client requests a web page in the project, a SessionBean
object is created.
The SessionBean can be accessed throughout a session by invoking
the method getSessionBean on the page bean
– Can then use the SessionBean object to access stored session
properties
To store information in the SessionBean
– Add properties to the SessionBean class
– To add a property
- Right click the SessionBean node in the Outline window
- Select Add > Property to display the New Property Pattern dialog
- Configure the property and click OK to create it
1992-2007 Pearson Education, Inc. All rights reserved.
1
<?xml version = "1.0" encoding = "UTF-8"?>
2
3
<!-- Fig. 26.26: Options.jsp -->
4
<!-- JSP file that allows the user to select a programming language. -->
5
<jsp:root version = "1.2" xmlns:f = "http://java.sun.com/jsf/core"
6
7
8
9
xmlns:h = "http://java.sun.com/jsf/html" xmlns:jsp =
"http://java.sun.com/JSP/Page" xmlns:ui = "http://www.sun.com/web/ui">
<jsp:directive.page contentType = "text/html; charset = UTF-8"
pageEncoding = "UTF-8"/>
10
<f:view>
11
12
13
14
15
16
17
Outline
Options.jsp
(1 of 5 )
<ui:page binding = "#{Options.page}" id = "page">
<ui:html binding = "#{Options.html}" id = "html">
<ui:head binding = "#{Options.head}" id = "head">
<ui:link binding = "#{Options.link}" id = "link"
url = "/resources/stylesheet.css"/>
</ui:head>
<ui:body binding = "#{Options.body}" id = "body"
18
19
20
21
22
23
24
style = "-rave-layout: grid">
<ui:form binding = "#{Options.form}" id = "form">
<ui:label binding = "#{Options.languageLabel}" for =
"languageList" id = "languageLabel" style =
"font-size: 16px; font-weight: bold; left: 24px; top:
24px; position: absolute" text = "Select a
programming language:"/>
25
26
27
<ui:radioButtonGroup binding = "#{Options.languageList}"
id = "languageList" items =
"#{Options.languageListOptions.options}" style =
28
123
"left: 24px; top: 48px; position: absolute"/>
2007 Pearson Education,
Inc. All rights reserved.
29
<ui:button action = "#{Options.submit_action}" binding =
30
"#{Options.submit}" id = "submit" style = "left:
31
32
23px; top: 192px; position: absolute" text =
"Submit"/>
33
<ui:staticText binding = "#{Options.responseLabel}" id =
34
35
36
"responseLabel" rendered = "false" style =
"font-size: 16px; font-weight: bold; height: 24px;
left: 24px; top: 24px; position: absolute;
37
width: 216px"/>
38
id = "numSelectedLabel" rendered = "false" style =
"left: 24px; top: 96px; position: absolute" text =
41
"Number of selections so far:"/>
42
<ui:staticText binding = "#{Options.numSelected}" id =
43
44
"numSelected" rendered = "false" style = "left:
192px; top: 96px; position: absolute" text =
45
"#{SessionBean.numSelections}"/>
49
50
Outline
Options.jsp
(2 of 5 )
<ui:staticText binding = "#{Options.numSelectedLabel}"
39
40
46
47
48
124
<ui:hyperlink action = "#{Options.languagesLink_action}"
binding = "#{Options.languagesLink}" id =
"languagesLink" rendered = "false" style = "left:
24px; top: 144px; position: absolute" text = "Click
here to choose another language."/>
2007 Pearson Education,
Inc. All rights reserved.
51
52
<ui:hyperlink binding = "#{Options.recommendationsLink}"
id = "recommendationsLink" rendered = "false" style =
53
54
55
"left: 24px; top: 168px; position: absolute" text =
"Click here to get book recommendations." url =
"/faces/Recommendations.jsp"/>
56
57
58
</ui:form>
</ui:body>
</ui:html>
59
</ui:page>
60
</f:view>
61 </jsp:root>
125
Outline
Options.jsp
(3 of 5 )
2007 Pearson Education,
Inc. All rights reserved.
126
Outline
Options.jsp
(4 of 5 )
2007 Pearson Education,
Inc. All rights reserved.
127
Outline
Options.jsp
(5 of 5 )
2007 Pearson Education,
Inc. All rights reserved.
128
Fig. 26.27 | New Property dialog for adding a property to the SessionBean.
2007 Pearson Education, Inc. All rights reserved.
129
Fig. 26.28 | Bind to Data dialog.
2007 Pearson Education, Inc. All rights reserved.
1
2
// Fig. 26.29: SessionBean.java
// SessionBean file for storing language selections.
3
4
package session;
5
import com.sun.rave.web.ui.appbase.AbstractSessionBean;
6
7
8
9
10
11
import java.util.Properties;
import javax.faces.FacesException;
public class SessionBean extends AbstractSessionBean
{
private int __placeholder;
12
13
14
private void _init() throws Exception
{
15
16
// empty body
} // end method _init
17
18
19
20
public SessionBean()
{
// empty constructor
21
22
23
24
25
} // end constructor
26
27
} // end method getApplicationBean
130
Outline
SessionBean.java
(1 of 3 )
protected ApplicationBean getApplicationBean()
{
return (ApplicationBean1) getBean( "ApplicationBean" );
2007 Pearson Education,
Inc. All rights reserved.
28
29
public void init()
{
30
super.init();
31
32
33
try
{
_init();
34
35
36
} // end try
catch ( Exception e )
{
131
Outline
SessionBean.java
(2 of 3 )
log( "SessionBean Initialization Failure", e);
throw e instanceof FacesException ? (FacesException) e:
37
38
new FacesException( e) ;
39
40
} // end catch
41
42
43
} // end method init
44
45
46
47
48
{
49
{
50
51
// empty body
} // end method activate
52
53
public void destroy()
54
{
55
56
// empty body
} // end method destroy
public void passivate()
// empty body
} // end method passivate
public void activate()
2007 Pearson Education,
Inc. All rights reserved.
57
132
58
59
private int numSelections = 0; // stores number of unique selections
60
public int getNumSelections()
61
62
63
64
65
{
66
{
67
68
this.numSelections = numSelections;
} // end method setNumSelections
69
70
71
72
73
74
75
76
return this.numSelections;
} // end method getNumSelections
SessionBean.java
(3 of 3 )
public void setNumSelections( int numSelections )
// Stores key-value pairs of selected languages
private Properties selectedLanguages = new Properties();
public Properties getSelectedLanguages()
{
return this.selectedLanguages;
} // end method getSelectedLanguages
Outline
Manually coded
Properties
object
77
78
79
80
81
public void setSelectedLanguages( Properties selectedLanguages )
{
this.selectedLanguages = selectedLanguages;
} // end method setSelectedLanguages
82 } // end class SessionBean
2007 Pearson Education,
Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Fig. 26.30: Options.java
// Page bean that stores language selections in a SessionBean property.
package session;
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
com.sun.rave.web.ui.appbase.AbstractPageBean;
com.sun.rave.web.ui.component.Body;
com.sun.rave.web.ui.component.Form;
com.sun.rave.web.ui.component.Head;
com.sun.rave.web.ui.component.Html;
com.sun.rave.web.ui.component.Link;
com.sun.rave.web.ui.component.Page;
javax.faces.FacesException;
com.sun.rave.web.ui.component.RadioButtonGroup;
com.sun.rave.web.ui.component.Hyperlink;
com.sun.rave.web.ui.component.Button;
com.sun.rave.web.ui.component.Label;
com.sun.rave.web.ui.component.StaticText;
com.sun.rave.web.ui.model.SingleSelectOptionsList;
java.util.Properties;
javax.servlet.http.Cookie;
javax.servlet.http.HttpServletRequest;
javax.servlet.http.HttpSession;
133
Outline
Options.java
(1 of 6 )
2007 Pearson Education,
Inc. All rights reserved.
24 public class Options extends AbstractPageBean
25 {
26
private int __placeholder;
27
28
private void _init() throws Exception
29
30
31
32
33
34
35
{
languageListOptions.setOptions(
new com.sun.rave.web.ui.model.Option[]
{
Outline
Options.java
(2 of 6 )
new com.sun.rave.web.ui.model.Option( "Java", "Java" ),
new com.sun.rave.web.ui.model.Option( "C", "C" ),
new com.sun.rave.web.ui.model.Option( "C++", "C++" ),
new com.sun.rave.web.ui.model.Option( "Visual Basic 2005",
"Visual Basic 2005" ),
new com.sun.rave.web.ui.model.Option( "Visual C# 2005",
36
37
38
"Visual C# 2005" )
39
40
41
42
43
44
45
134
}
);
} // end method init
// To save space, we omitted the code in lines 44-219. The complete
// source code is provided with this chapter's examples.
46
2007 Pearson Education,
Inc. All rights reserved.
220
private Properties books = new Properties();
221
222
223
public Options()
{
224
// initialze the Properties object of values to be stored in
225
226
227
228
// the session bean.
books.setProperty( "Java", "0-13-148398-6" );
books.setProperty( "C", "0-13-142644-3" );
books.setProperty( "C++", "0-13-185757-6" );
229
books.setProperty( "Visual Basic 2005", "0-13-186900-0" );
230
231
books.setProperty( "Visual C# 2005", "0-13-152523-9" );
} // end constructor
232
233
protected ApplicationBean getApplicationBean()
234
235
236
135
Outline
Options.java
(3 of 6 )
{
return (ApplicationBean) getBean( "ApplicationBean" );
} // end method getApplicationBean
237
238
239
protected RequestBean getRequestBean()
{
240
241
return (RequestBean) getBean( "RequestBean" );
} // end method getRequestBean
242
243
244
protected SessionBean getSessionBean()
{
245
246
return (SessionBean) getBean( "SessionBean" );
} // end method getSessionBean
247
2007 Pearson Education,
Inc. All rights reserved.
248
public void init()
249
{
250
super.init();
251
252
try
{
_init();
253
} // end try
catch ( Exception e )
{
254
255
256
257
log( "Options Initialization Failure", e );
258
259
throw e instanceof FacesException ? (FacesException) e:
new FacesException( e );
260
} // end catch
261
} // end method init
262
263
public void preprocess()
264
265
266
267
268
269
270
271
272
273
274
{
275
276
277
// empty body
} // end method destroy
136
Outline
Options.java
(4 of 6 )
// empty body
} // end method preprocess
public void prerender()
{
// empty body
} // end method prerender
public void destroy()
{
2007 Pearson Education,
Inc. All rights reserved.
278
// action handler for the submit button, stores selected languages
279
// in session scope for retrieval when making book recommendations.
280
public String submit_action()
281
{
282
String msg = "Welcome to sessions!
137
Outline
You ";
Options.java
283
284
// if the user made a selection
285
if ( getLanguageList().getSelected() != null )
286
{
287
String language = languageList.getSelected().toString();
288
msg += "selected " + language + ".";
(5 of 6 )
289
290
// get ISBN number of book for the given language.
291
String ISBN = books.getProperty( language );
292
293
// add the selection to the SessionBean's Properties object
294
Properties selections = getSessionBean().getSelectedLanguages();
295
Object result = selections.setProperty( language, ISBN );
Add a
recommendation
296
297
// increment numSelections in the SessionBean and update
298
// selectedLanguages if the user has not made this selection
299
// before
300
if ( result == null )
301
{
302
int numSelected = getSessionBean().getNumSelections();
303
getSessionBean().setNumSelections( ++numSelected );
304
305
} // end if
} // end if
2007 Pearson Education,
Inc. All rights reserved.
306
307
else
msg += "did not select a language.";
308
309
310
responseLabel.setValue( msg );
languageList.setRendered( false );
311
languageLabel.setRendered( false );
312
313
314
submit.setRendered( false );
responseLabel.setRendered( true );
numSelectedLabel.setRendered( true );
315
numSelected.setRendered( true );
316
languagesLink.setRendered( true );
317
318
319
recommendationsLink.setRendered( true );
return null;
} // end method submit_action
320
321
322
// redisplay the components used to allow the user to select a
// language.
323
public String languagesLink_action() {
324
325
326
327
responseLabel.setRendered( false );
numSelectedLabel.setRendered( false );
numSelected.setRendered( false );
languagesLink.setRendered( false );
328
329
recommendationsLink.setRendered( false );
languageList.setRendered( true );
330
languageLabel.setRendered( true );
331
submit.setRendered( true );
138
Outline
Options.java
(6 of 6 )
332
return null;
333
} // end method languagesLink_action
334 } // end class Options
2007 Pearson Education,
Inc. All rights reserved.
139
Software Engineering Observation 26.2
A benefit of using SessionBean properties
(rather than cookies) is that they can store any
type of object (not just Strings) as attribute
values. This provides you with increased
flexibility in maintaining client state
information.
2007 Pearson Education, Inc. All rights reserved.
1
<?xml version = "1.0" encoding = "UTF-8"?>
2
3
4
<!-- Fig. 26.31: Recommendations.jsp -->
<!-- JSP file that displays book recommendations based on language
5
6
<!-- selections stored in session scope. -->
<jsp:root version = "1.2" xmlns:f = "http://java.sun.com/jsf/core"
7
8
xmlns:h = "http://java.sun.com/jsf/html" xmlns:jsp =
"http://java.sun.com/JSP/Page" xmlns:ui = "http://www.sun.com/web/ui">
9
10
11
<jsp:directive.page contentType = "text/html; charset = UTF-8"
pageEncoding = "UTF-8"/>
<f:view>
12
13
14
15
16
17
18
Recommendations
.jsp
(1 of 2 )
<ui:link binding = "#{Recommendations.link}" id = "link"
url = "/resources/stylesheet.css"/>
</ui:head>
<ui:body binding = "#{Recommendations.body}" id = "body"
style = "-rave-layout: grid">
<ui:form binding = "#{Recommendations.form}" id = "form">
21
<ui:label binding = "#{Recommendations.languageLabel}"
25
Outline
<ui:page binding = "#{Recommendations.page}" id = "page">
<ui:html binding = "#{Recommendations.html}" id = "html">
<ui:head binding = "#{Recommendations.head}" id = "head">
19
20
22
23
24
140
for = "booksListBox" id = "languageLabel" style =
"font-size: 20px; font-weight: bold; left: 24px; top:
24px; position: absolute" text = "Recommendations"/>
<ui:listbox binding = "#{Recommendations.booksListBox}"
26
27
id = "booksListBox" items = "#{Recommendations.
booksListBoxDefaultOptions.options}" rows = "6"
28
style = "left: 24px; top: 72px; position: absolute;
29
width: 360px"/>
2007 Pearson Education,
Inc. All rights reserved.
30
<ui:hyperlink action = "case1" binding =
31
"#{Recommendations.optionsLink}" id = "optionsLink"
32
style = "left: 24px; top: 192px; position: absolute"
33
text = "Click here to choose another language."/>
34
</ui:form>
35
</ui:body>
36
</ui:html>
37
</ui:page>
38
</f:view>
39 </jsp:root>
141
Outline
Recommendations
.jsp
(2 of 2 )
2007 Pearson Education,
Inc. All rights reserved.
1
// Fig. 26.32: Recommendations.java
2
3
// Page bean that displays book recommendations based on a SessionBean
// property.
4
package session;
5
6
import com.sun.rave.web.ui.appbase.AbstractPageBean;
7
8
import com.sun.rave.web.ui.component.Body;
import com.sun.rave.web.ui.component.Form;
9
import com.sun.rave.web.ui.component.Head;
10 import com.sun.rave.web.ui.component.Html;
142
Outline
Recommendations
.java
(1 of 4 )
11 import com.sun.rave.web.ui.component.Link;
12 import com.sun.rave.web.ui.component.Page;
13 import javax.faces.FacesException;
14 import com.sun.rave.web.ui.component.Listbox;
15
16
17
18
import
import
import
import
com.sun.rave.web.ui.component.Label;
com.sun.rave.web.ui.component.Hyperlink;
com.sun.rave.web.ui.model.DefaultOptionsList;
java.util.Enumeration;
19 import com.sun.rave.web.ui.model.Option;
20 import java.util.Properties;
21
22 public class Recommendations extends AbstractPageBean
23 {
24
private int __placeholder;
25
26
private void _init() throws Exception
27
{
28
// empty body
29
} // end method _init
30
2007 Pearson Education,
Inc. All rights reserved.
31
// To save space, we omitted the code in lines 31-150. The complete
32
33
// source code is provided with this chapter's examples.
151
public Recommendations()
152
153
{
154
155
} // end constructor
156
protected RequestBean getRequestBean()
157
{
// empty constructor
Outline
Recommendations
.java
(2 of 4 )
return (RequestBean) getBean( "RequestBean" );
158
159
160
} // end method getRequestBean
161
protected ApplicationBean getApplicationBean()
162
163
164
165
{
166
167
168
protected SessionBean getSessionBean()
{
return (SessionBean) getBean( "SessionBean" );
169
170
171
172
173
174
175
176
} // end method getSessionBean
177
143
return (ApplicationBean) getBean( "ApplicationBean" );
} // end method getApplicationBean
public void init()
{
super.init();
try
{
_init();
} // end try
2007 Pearson Education,
Inc. All rights reserved.
catch ( Exception e )
{
178
179
log( "Recommendations Initialization Failure", e );
throw e instanceof FacesException ? (FacesException) e:
180
181
144
Outline
new FacesException( e );
182
183
184
185
186
} // end catch
} // end method init
187
188
189
{
public void preprocess()
Recommendations
.java
(3 of 4 )
// empty body
} // end method preprocess
190
191
192
193
public void prerender()
{
//retrieve user's selections and number of selections made
194
Properties languages = getSessionBean().getSelectedLanguages();
195
196
197
198
Enumeration selectionsEnum = languages.propertyNames();
int numSelected = getSessionBean().getNumSelections();
Option [] recommendations;
199
200
// if at least one selection was made
201
202
if ( numSelected > 0 )
{
203
Obtains the objects
needed to retrieve
the users selections
recommendations = new Option[ numSelected ];
204
2007 Pearson Education,
Inc. All rights reserved.
205
for ( int i = 0; i < numSelected; i++ )
206
{
145
207
String language = (String) selectionsEnum.nextElement() ;
208
209
recommendations[ i ] = new Option( language +
"How to Program. ISBN#:" +
210
211
212
languages.getProperty( language ) );
} // end for
} // end if
213
214
215
216
else
{
recommendations = new Option[ 1 ];
recommendations[ 0 ] = new Option( "No recommendations.
217
218
219
"Please select a language." );
} // end else
220
booksListBox.setItems( recommendations );
221
222
223
224
225
226
Outline
Creates
recommendations
for the Recommendations
user
.java
(4 of 4 )
" +
} // end method prerender
public void destroy()
{
// empty body
} // end method destroy
227 } // end class Recommendations
2007 Pearson Education,
Inc. All rights reserved.