JavaServer Faces Web Applications

laboredbumbaileyDéveloppement de logiciels

7 juin 2012 (il y a 2 années et 2 mois)

804 vue(s)



2007 Pearson Education, Inc. All rights reserved.

1

26

JavaServer ™
Faces Web
Applications



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 Netbeans.


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


Introduction

26.2



Java Web Technologies



26.2.1



Servlets



26.2.2



JavaServer Pages



26.2.3



JavaServer Faces



26.2.4



Web Technologies in Netbeans


26.3



Creating and Running a Simple Application in Netbean


26.3.1



Examining a JSP File



26.3.2



Examining a Page Bean File



26.3.3



Event
-
Processing Life Cycle



26.3.4



Relationship Between the JSP and Page Bean
Files



26.3.5



Examining the XHTML Generated by a Java Web
Application



26.3.6



Building a Web Application in Netbeans




2007 Pearson Education, Inc. All rights reserved.

6

26.4



JSF Components



26.4.1



Text and Graphics Components



26.4.2



Validation Using Validator Components and
Custom Validators


26.5



Session Tracking



26.5.1



Cookies



26.5.2



Session Tracking with the
SessionBean

Object

26.6



Wrap
-
Up


26.7



Web Resources



1992
-
2007 Pearson Education, Inc. All rights reserved.

7

26.1 Introduction


This chapter assumes Java programming
experience


See
Java How to Program, Seventh Edition


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 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


Netbeans + Visual Web Pack


Drag
-
and
-
drop web
-
application GUI development


Business logic placed in separate Java classes



1992
-
2007 Pearson Education, Inc. All rights reserved.

9

26.2.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.

10

26.2.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.

11

26.2.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.

12

26.2.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.

13

26.2.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.

14

26.2.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.

15

26.2.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.

16

26.2.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



2007 Pearson Education, Inc. All rights reserved.

17

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.



1992
-
2007 Pearson Education, Inc. All rights reserved.

18

26.2.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.

19

26.2.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.

20

26.2.4 Web Technologies in Netbeans


Netbeans 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


Netbeans 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 Netbeans represents a web page
and has a corresponding JavaBean class called the page
bean



1992
-
2007 Pearson Education, Inc. All rights reserved.

21

26.2.4 Web Technologies in Netbeans


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 Netbeans has a page
bean, a
RequestBean
, a
SessionBean

and an
ApplicationBean



1992
-
2007 Pearson Education, Inc. All rights reserved.

22

26.2.4 Web Technologies in Netbeans


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.

23

26.3 Creating and Running a Simple
Application in Netbeans


Static Text

components display text that cannot
be edited by the user



2007 Pearson Education,
Inc. All rights reserved.

24


1

<?
xml version =

"1.0"

encoding =

"UTF
-
8"
?>


2



3

<!
--
Fig.

26.1: Time.jsp
--
>


4

<!
--
JSP file generated by Netbeans that displays
--
>


5

<!
--
the current time on the web server
--
>


6

<jsp:root version =

"1.2"



7



xmlns:f =

"http://java.sun.com/jsf/core"



8


xmlns:h =

"http://java.sun.com/jsf/html"



9


xmlns:jsp =

"http://java.sun.com/JSP/Page"


10


xmlns:webuijsf =

"http://www.sun.com/webui/webuijsf"
>

11


<jsp:
dir
ective
.page contentType =

"text/html;charset=UTF
-
8"


12


pageEncoding
=

"UTF
-
8"

/>

13


<f:view>

14



<webuijsf:page binding =

"#{Time.page1}"

id =

"page1"
>

15


<webuijsf:html binding =

"#{Time.html1}"

id =

"html1"
>

16



<webuijsf:head binding =

"#{Time.head1}"

id =

"head1"


17




title =

"Web Time: A Simple Example"
>


18



<webuijsf:link binding =

"#{Time.link1}"

id =

"link1"


19




url =

"/resources/styl
esheet.css"
/>


20




<
webuijsf:meta content =

"60"

httpEquiv =

"refresh"

/>


Outline

Time.jsp


(1 of 2 )


Tag libraries available for
use in this web application

Configure
head

section of
web page



2007 Pearson Education,
Inc. All rights reserved.

25

21


</webuijsf:head>


22


<webuijsf:body binding =

"#{Time.body1}"

id =
"body1"


23


style =

"
-
rave
-
layout: grid"
>

24


<webuijsf:form binding =

"#{Time.form1}"

id =

"form1"
>

25


<webuijsf:staticText binding =

"#{Time.timeHeader}"

26



id =

"timeHeader"

style =
"font
-
size: 18px;


27




left: 24px; top: 24px; position: absolute"


28





text =

"Current time on the web server:"

/>


29


<webuijsf:staticText binding =

"#{Time.clockText}"

30


id =

"clockText"

style =
"background
-
color: black;

31


color: yellow;
font
-
size: 18px; left: 24px;

32


top: 48px; position: absolute"

/>

33

</webuijsf:form>

34

</webuijsf:body>

35

</webuijsf:html>

36

</webuijsf:page>

37

</f:view>

38

</jsp:root
>


Outline

Time.jsp


(2 of 2 )


Set up a
Static
Text

element



1992
-
2007 Pearson Education, Inc. All rights reserved.

26

26.3.1 Examining a JSP File


Netbeans 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 Netbeans include t
he 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.

27

26.3.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
webuijsf

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.

28

26.3.1 Examining a JSP File


webuijsf:head

element


title

attribute that specifies the page’s title


webuijsf:link

element


can be used to specify the CSS stylesheet used by a page


webuijsf:body

element


defines the body of the page


webuijsf:form

element


defines a form in a page.


webuijsf:staticText

component


displays text that does not change



1992
-
2007 Pearson Education, Inc. All rights reserved.

29

26.3.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


webuijsf: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
webuijsf:staticText

represented
as part of the corresponding
span

element’s
style

attribute



2007 Pearson Education, Inc. All rights reserved.

30

Fig. 26.2

|
Sample JSF component tree.



1992
-
2007 Pearson Education, Inc. All rights reserved.

31

26.3.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


A
webuijsf:staticText

component is a
StaticText

object (package
com.sun.webui.jsf.component
).



2007 Pearson Education,
Inc. All rights reserved.

32

Outline

Time.java


(1 of 8 )



1

// Fig.

26.3: Time.java


2

// Page bean file that sets clockText to the time on the Web server.


3

package
webtime;


4



5

import
com.sun.rave.web.ui.appbase.AbstractPageBean;


6

import
com.sun.webui.jsf.component.Body;


7

import
com.sun.webui.jsf
.component.Form;


8

import
com.sun.webui.jsf.component.Head;


9

import
com.sun.webui.jsf.component.Html;

10

import
com.sun.webui.jsf.component.Link;

11

import
com.sun.webui.jsf.component.Meta;

12

import
com.sun.webui.jsf.component.Page;

13

import
com.sun.webui.jsf.component.StaticText;

14

import
java.text.DateFormat;

15

import
java.util.Date;

16

import
javax.faces.FacesException;

17


18

public class
Time
extends
AbstractPageBean

19

{

20


private int
__placeholder;




2007 Pearson Education,
Inc. All rights reserved.

33

21



22

// auto
-
generated component initialization method.

23


private

v
oid
_init()
throws
Exception

24

{

25

}
// end method _init

26



27


private
Page page1 =
new
Page();

28



29


public

Page getPage1()

30

{

31


return
page1;

32

}
// end method getPage1

33



34


public

void

setPage1( Page p )

35

{

36


this
.page1 = p;

37

}
// end method setPage1

38



39


private
Html html1 =
new
Html();

40



41


public
Html getHtml1()

42

{

43


return
html1;

44

}
// end method getHtml1

45



46


public void
setHtml1( Html h )

47

{

48


this
.html1 = h;

49

}
// end method setHtml1

50



51


private
Head head1 =
new
Head();

52



53


public
Head getHead1()

54

{

55


return
head1;

56

}
// end metho
d getHead1


Outline

Time.java


(2 of 8 )




2007 Pearson Education,
Inc. All rights reserved.

34

57



58


public void
setHead1( Head h )

59

{

60


this
.head1 = h;

61

}
// end method setHead1

62



63


private
Link link1 =
new
Link();

64



65


public
Link getLink1()

66

{

67


return
link1;

68

}
// e
nd method getLink1

69



70


public void
setLink1( Link l )

71

{

72


this
.link1 = l;

73

}
// end method setLink1

74



75


private
Body body1 =
new
Body();

76



77


public
Body getBody1()

78

{

79


return
b
ody1;

80

}
// end method getBody1

81



82


public void

setBody1( Body b )

83

{

84


this
.body1 = b;

85

}
// end method setBody1


Outline

Time.java


(3 of 8 )




2007 Pearson Education,
Inc. All rights reserved.

35

86



87


private
Form form1 = new Form();

88



89


public
Form getForm1()

90

{

91


return
form1;

92

}
// end method getForm1

93



94


public void
setForm1( Form f )

95

{

96


this
.form1 = f;

97

}
// e
nd method setForm1

98


99


private
StaticText timeHeader =
new
StaticText();

100


101


public
StaticText getTimeHeader()

102

{

103


return
timeHeader;

104

}
// end method getTimeHeader

105


106


public void
setTimeHeader(
StaticText st )

107

{

108


this
.timeHeader = st;

109

}
// end method setTimeHeader

110



Outline

Time.java


(4 of 8 )




2007 Pearson Education,
Inc. All rights reserved.

36

111


private

StaticText clockText =

new

StaticText();

112


113


public
StaticText getClockText()

114

{

115


return
clockText;

116

}
// end method getClockText

117


118


public void
setClockText( StaticText st )

119

{

120


this
.clockText = st;

121

}
// end method setClockText

122


123


private
Meta meta1 =
new
Meta();

124


125


public
Meta getMeta1()

126

{

127


return
meta1;

128

}
// end method getMeta1


Outline

Time.java


(5 of 8 )


Code that was
inserted by the
designer to create a
StaticText

object



2007 Pearson Education,
Inc. All rights reserved.

37

129


130


public void
setMeta1( Meta m )

131

{

132


this
.meta1 = m;

133

}
// end method setMeta1

134



135


public

Time()

136

{

137

}
// end Time constructor

138



139

// initializes page content

140


pu
blic void
init()

141

{

142


super
.init();

143



144


try

145

{

146

_init();

147

}
// end try

148


catch
( Exception e )

149

{

150

log(
"Time Initialization Failure"
, e );

151


throw
e instanceof FacesException ? ( FacesException ) e :

152


new
FacesException( e );

153

}
// end catch

154

}
// end method init


Outline

Time.java


(6 of 8 )




2007 Pearson Education,
Inc. All rights reserved.

38

155



156

// method called when postback occurs

157


public void
preprocess()

158

{

159

}
// end method preprocess

160



161

// method called before the page is rendered

162


public void
prerender()

163

{

164



clockText.setValue( DateFormat.getTimeInstance(

165



DateFormat.LONG

).format(

new

Date() ) );


166

}
// end method prerender

167




Outline

Time.java


(7 of 8 )


Programmatically
change the text in
the
StaticText

object



2007 Pearson Education,
Inc. All rights reserved.

39

168

// method called after rendering completes, if init was called

169


public void
destroy()

170

{

171

}
// end method destroy

172


173

// return a reference to the scoped data bean

174


protected
SessionBean1 getSessionBean1(
)

175

{

176


return
( SessionBean1 ) getBean(
"SessionBean1"
);

177

}
// end method getSessionBean1

178


179

// return a reference to the scoped data bean

180


protected
ApplicationBean1 getApplicationBean1()

181

{

182



return
( ApplicationBean1 ) getBean(
"ApplicationBean1"
);

183

}
// end method getApplicationBean1

184


185

// return a reference to the scoped data bean

186


protected
RequestBean1 getRequestBean1()

187

{

188


return

( Requ
estBean1 ) getBean(

"RequestBean1"
);

189

}
// end method getRequestBean1

190

}
// end class Time


Outline

Time.java


(8 of 8 )




2007 Pearson Education,
Inc. All rights reserved.

40

Outline

Time.java




1992
-
2007 Pearson Education, Inc. All rights reserved.

41

26.3.3 Event
-
Processing Life Cycle


Netbeans 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.

42

26.3.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.

43

26.3.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.

44

26.3.5 Examining the XHTML Generated
by a Java Web Application




2007 Pearson Education,
Inc. All rights reserved.

45


1

<!DOCTYPE html PUBLIC
"
-
//W3C//DTD XHTML 1.0 Transitional//EN"


2


"http://www.w3.org/TR/xhtml1/DTD/xhtml1
-
transitional.dtd"
>


3

<html xmlns =
"http://www.w3.org/1999/xhtml"


4


xmlns:wairole =
"http://www.w3.org/2005/01/wai
-
rdf/GUIRoleTaxonomy
#"


5


xmlns:waistate =
"http://www.w3.org/2005/07/aaa"
>


6

<head>


7


<meta content =

"no
-
cache"

http
-
equiv =

"Pragma"

/>


8


<meta content =

"no
-
cache"
http
-
equiv =

"Cache
-
Control"
/>


9


<meta content =

"no
-
store"
http
-
equiv =

"Cache
-
Control"

/>

10


<meta content =
"max
-
age=0"
http
-
equiv =
"Cache
-
Control"

/>

11


<meta content =
"1"

http
-
equiv =

"Expires"

/>

12


<title>
Web Time: A Simple Example
</title>

13


<link rel =
"stylesheet"

type =

"text/css"

hr
ef =
"/WebTime/theme/

14


com/sun/webui/jsf/suntheme/css/css_master.css"

/>

15


<link rel =
"stylesheet"

type =

"text/css"

href =

"/WebTime/theme/

16


com/sun/webui/jsf/suntheme/css/ie7.css"

/>

17


<script type =
"text/jav
ascript"
>

18

djConfig = {

19


"isDebug"
:
false
,

20


"parseWidgets"
:
false
,

21


"debugAtAllCosts"
:
false

22

};

23

</script>

24


<script type =

"text/javascript"

25


sr
c =
"/WebTime/theme/META
-
INF/dojo/dojo.js"
></script>


Outline

Time.html


(1 of 2 )




2007 Pearson Education,
Inc. All rights reserved.

46

26


<script type =

"text/javascript"

27


src =
"/WebTime/theme/META
-
INF/json/json.js"
></script>

28


<script type =

"text/javascript"

29


src =

"/WebTime/theme/META
-
INF/prototype/prototype.js"
></script>

30


<script
type =

"text/javascript"


31


src =

"/WebTime/theme/META
-
INF/com_sun_faces_ajax.js"
></script>

32


<script type =
"text/javascript"
>

33

dojo.hostenv.setModulePrefix(
"webui.suntheme"
,

34


"/WebTime/theme/com/sun/web
ui/jsf/suntheme/javascript"
);

35

dojo.require(
'webui.suntheme.*'
);

36


</script>

37


<link id =
"link1"
rel =

"stylesheet"

type =

"text/css"

38


href =
"/WebTime/resources/stylesheet.css"

/>

39


<meta id =
"j_i
d_id7"

http
-
equiv =
"refresh"

content =
"60"
/>

40

</head>

41


<body id =
"body1"

style =

"
-
rave
-
layout:grid"

onload=
""

onunload=
""
>

42


<form id =

"form1"

class =
"form"
method =

"post"

43


action =

"/WebTime/faces/Time.jsp"

44


enctype =
"application/x
-
www
-
form
-
urlencoded"
>

45


<span id =
"form1:timeHeader"

style =
"font
-
size: 18px; left: 24px;

46



top: 24px; position: absolute"
>
Current time on the web server:


47


</span>



48


<span id =

"form1:clockText"

style =

"background
-
color: black;


49



color: yellow; font
-
size: 18px; left: 24px; top: 48px;


50



position: absolute"
>
12:30:49 PM EDT
</span>



51


<input id =

"form1_hidden"

name =

"form1_hidden"

52


value =

"form1_hidden"

type =
"hidden"

/>

53


<input type =
"hidden"
name =

"javax.faces.ViewState"


54


id =
"javax.faces.ViewState"

value =

"
j_id173:j_id174"

/>

55

</form>

56


<script type
=
"text/javascript"
>

57

webui.suntheme.common.body = new webui.suntheme.body(

58


'/Time.jsp'
,
'/WebTime/faces/Time.jsp'
,
null
,
null
,

59


'com_sun_webui_uti
l_FocusManager_focusElementId'
);
</script>

60

</body>

61

</html>


Outline

Time.html


(2 of 2 )




2007 Pearson Education, Inc. All rights reserved.

47

23.6.6 Building a Web Application in
Netbeans




2007 Pearson Education, Inc. All rights reserved.

48

Fig. 26.5

|
Visual Editor

window in
Design

mode.



2007 Pearson Education, Inc. All rights reserved.

49

Fig. 26.6

|
Palette

in Netbeans.



2007 Pearson Education, Inc. All rights reserved.

50

Fig. 26.7

|

Projects

window for the
WebTime

project.




2007 Pearson Education, Inc. All rights reserved.

51

Fig. 26.8

|

JSP file generated for Page1 by Netbeans.



2007 Pearson Education, Inc. All rights reserved.

52

Fig. 26.9

|

Page bean file for
Page1.jsp

generated by Netbeans.




2007 Pearson Education, Inc. All rights reserved.

53

Fig. 26.10

|

Time.jsp

after inserting the first
Static Text

component.



2007 Pearson Education, Inc. All rights reserved.

54

Fig. 26.11

|

Time.jsp

after adding the second
Static

Text

component.




2007 Pearson Education, Inc. All rights reserved.

55

Fig. 26.12

|

Outline

window in Netbeans.




2007 Pearson Education, Inc. All rights reserved.

56

Error
-
Prevention Tip 26.1

If you have trouble building your project
due to errors in the Netbeans
-
generated
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
<Shift>

F11
.



1992
-
2007 Pearson Education, Inc. All rights reserved.

57

26.4 JSF Components




2007 Pearson Education, Inc. All rights reserved.

58


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.13

|
Commonly used JSF components.



1992
-
2007 Pearson Education, Inc. All rights reserved.

59

26.4.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.

60

26.4.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.

61

26.4.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
.



2007 Pearson Education,
Inc. All rights reserved.

62


1

<?xml version =

"1.0"

encoding =
"UTF
-
8"

?>


2



3

<!
--
Fig.

26.14: WebComponents.jsp
--
>


4

<!
--
Registration form that demonstrates JSF components
--
>


5

<jsp:root version =

"1.2"


6


xmlns:f =
"http://java.sun.com/jsf/core"



7


xmlns:h =

"http://java.sun.com/jsf/html"



8


xmlns:jsp =

"http://java.sun.com/JSP/Page"



9


xmlns:webuijsf =

"http://www.sun.com/webui/webuijsf"
>

10


<jsp:directive.page contentType =

"text/html;charset=UTF
-
8"


11


pageEncoding =

"UTF
-
8"

/>

12


<f:view>

13


<webuijsf:page binding =

"#{WebComponents.page1}"
id =

"page1"
>

14


<webuijsf:html binding =
"#{WebComponents.html1}"

id =
"html1"
>

15


<webuijsf:head binding =

"#{WebComponents.head1}"

id =

"head1"

16


titl
e =
"Sample Registration Form"
>

17


<webuijsf:link binding =

"#{WebComponents.link1}"


18


id =
"link1"

url =

"/resources/stylesheet.css"

/>

19


</webuijsf:head>

20


<webuijsf:body binding =

"#{WebComponents
.body1}"

id =

"body1"

21


style =

"
-
rave
-
layout: grid"
>

22


<webuijsf:form binding =

"#{WebComponents.form1}"


23


id =

"form1"
>

24


<webuijsf:staticText binding =
"#{WebComponents.header}"


25



id =

"header"

style =

"font
-
size: 18px; left: 24px;

26

top: 24px; position: absolute; width: 264px"

27


text =

"This is a sample registration form"
/>


Outline

WebComponents
.jsp


(1 of 6 )




2007 Pearson Education,
Inc. All rights reserved.

63

28

<webuijsf:staticText

29


binding =

"#{WebComponents.instructions}"


30


id =
"instructions"

style =
"font
-
size: 12px;

31


font
-
style: italic; left: 24px; top: 48px;

32



position: absolute"

33


text =

"Please fill in all fields and click Register"
/>

34



<webuijsf:image binding =

"#{WebComponents.userImage}"

35



id =
"userImage"

style =

"left: 24px; t
op: 72px;


36



position: absolute"

url =
"/resources/user.JPG"
/>


37


<h:panelGrid binding =

"#{WebComponents.gridPanel}"


38



columns =

"4"
id =

"gridPanel"

style =
"height: 96px;

39




left: 24px; top: 96px; position: absolute"


40



width =
"576"
>


41


<webuijsf:image binding =

"#{WebComponents.image1}"


42


id =
"i
mage1"

url =

"/resources/fname.JPG"
/>

43


<webuijsf:textField


44




binding =
"#{WebComponents.firstNameTextField}"

45



id =
"firstNameTextField"
/>



46


<webuijsf:image binding =

"#{WebComponents.image2}"


47


id =

"image2"
url =
"/resources/lname.JPG"
/>

48

<webuijsf:textField

49


binding =
"#{WebComponents
.lastNameTextField}"


50


id =

"lastNameTextField"

/>

51


<webuijsf:image binding =
"#{WebComponents.image4}"


52


id =
"image4"

url =
"/resources/email.JPG"

/>

53

<webu
ijsf:textField

54


binding =
"#{WebComponents.emailTextField}"


55


id =

"emailTextField"

/>

56


<webuijsf:image binding =

"#{WebComponents.image3}"



Outline

WebComponents
.jsp


(2 of 6 )


Designer generated
code for
Image

Designer generated
code for
Grid
Panel

Designer generated
code for
Text Field



2007 Pearson Education,
Inc. All rights reserved.

64

57


id =
"image3"

url =

"/resources/phone.JPG"

/>

58

<webuijsf:textField

59


binding =

"#{WebComponents.phoneTextField}"


60


id =

"phoneTextField"
/>

61


</h:panelGrid>

62


<webuijsf:image binding =

"#{WebComponents.image5}"


63


id =

"image5"

style =

"left: 24px; top: 216px;

64


position: absolute"

65


url =

"/resources/pu
blications.JPG"
/>

66


<webuijsf:staticText

67


binding =
"#{WebComponents.publicationLabel}"


68


id =

"publicationLabel"

style =
"font
-
size: 12px;

69


left: 216px; top: 216px;
position: absolute"

70


text =
"Which book would you like information about?"
/>

71


<webuijsf:dropDown


72




binding =
"#{WebComponents.booksDropDown}"



73



id =

"booksDropDown"

items =


74


"#{WebComponents.booksDropDownDefaultOptions.options}"


75



selected=
"#{WebComponents.booksDropDownDefaultOptions.

76





selectedValue}"
style =
"left: 24px; top: 240px;


77




position: absolute"
/>



Outline

WebComponents
.jsp


(3 of 6 )


Designer generated
code for
Drop
Down List



2007 Pearson Education,
Inc. All rights reserved.

65

78


<webuijsf:radioButtonGroup


79




binding =

"#{WebComponents.osRadioGroup}"


80




id =

"osRadioGroup"
items =


81



"#{WebComponents.osRadioGroupDefaultOptions.options}"


82




selected =
"#{WebComponents.osRadioGroupDefaultOptions.

83




selectedValue}"

style =

"left: 24px; top: 336px;


84



position:
absolute"

/>


85


<webuijsf:button binding =


86



"#{WebComponents.registerButton}"

id =

"registerButton"

87




style =
"left: 23px; top:
480px; position: absolute;


88




width: 100px"

text =

"Register"

/>


89


<webuijsf:image binding =

"#{WebComponents.image6}"


90


id =
"image6"

style =
"left: 24px; top: 312px;

91


position: absolute"

url =

"/resources/os.JPG"
/>


Outline

WebComponents
.jsp


(4 of 6 )


Designer generated
code for
Radio
Button Group

Designer generated
code for
Button



2007 Pearson Education,
Inc. All rights reserved.

66

92


<webuijsf:staticText binding =

"#{WebComponents.osLabel}"


93


id =

"osLabel"
style =
"font
-
size: 12px; left: 216px;

94


top: 312px; position: absolute"

95


text =

"What oper
ating system are you using?"
/>

96


<webuijsf:hyperlink


97




binding =

"#{WebComponents.deitelHyperlink}"


98



id =

"deitelHyperlink"

style =
"left: 24
px; top: 264px;

99




position: absolute"

target =

"_blank"


100



text =

"Click here to learn more about our books"


101




url =

"http://www.deitel.com"

/>



102

</webuijsf:form>

103

</webuijsf:body>

104

</webuijsf:html>

105

</webuijsf:page>

106

</f:view>

107

</jsp:root>


Outline

WebComponents
.jsp


(5 of 6 )


Designer generated
code for
hyperlink



2007 Pearson Education,
Inc. All rights reserved.

67



Outline

WebComponents
.jsp


(6 of 6 )




1992
-
2007 Pearson Education, Inc. All rights reserved.

68

26.4.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 Validator
s and
Long Range Validator
s


Determine whether numeric input falls within acceptable ranges


Package
javax.faces.validators

contains the
validator classes



1992
-
2007 Pearson Education, Inc. All rights reserved.

69

26.4.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.

70

26.4.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
webuijsf:message

component



1992
-
2007 Pearson Education, Inc. All rights reserved.

71

26.4.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.

72

26.4.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



2007 Pearson Education,
Inc. All rights reserved.

73


1

<?xml version =

"1.0"

encoding =

"UTF
-
8"
?>


2



3

<!
--
Fig. 26.15: Validation.jsp
--
>


4

<!
--
JSP that demonstrates validation of user input.
--
>


5

<jsp:root

version =

"1.2"


6


xmlns:f =

"http://java.sun.com/jsf/core"



7


xmlns:h =

"http:/
/java.sun.com/jsf/html"



8


xmlns:jsp =

"http://java.sun.com/JSP/Page"



9


xmlns:webuijsf =

"http://www.sun.com/webui/webuijsf"
>

10


<jsp:directive.page contentType =

"text/html;charset=UTF
-
8"


11


pageEncoding =
"UTF
-
8"
/>

12


<f:vie
w>

13


<webuijsf:page

binding =
"#{Validation.page1}"

id =
"page1"
>

14


<webuijsf:html

binding =
"#{Validation.html1}"

id =
"html1"
>

15


<webuijsf:head

binding =
"#{Validation.head1}"

id =
"head1"
>

16


<webuijsf:link

bindi
ng =
"#{Validation.link1}"

id =
"link1"


17


url =
"/resources/stylesheet.css"
/>

18

</webuijsf:head>

19


<webuijsf:body

binding =
"#{Validation.body1}"

id =
"body1"


20


style =
"
-
rave
-
layout: grid"
>

21



<webuijsf:form

binding =
"#{Validation.form1}"

id =
"form1"
>

22


<webuijsf:staticText

binding =
"#{Validation.headerText}"


23


id =
"headerText"

style =
"font
-
size: 14px; font
-
weight:

24

bo
ld; left: 24px; top: 24px; position: absolute"

25


text =
"Please fill out the following form:"
/>

26


<webuijsf:staticText

binding =

27


"#{Validation.instructionText}"

id =
"instructionText"

28



style =
"font
-
size: 12px; font
-
style: italic; left:

29


24px; top: 48px; position: absolute"

text =
"All fields


Outline

Validation.jsp


(1 of 6 )




2007 Pearson Education,
Inc. All rights reserved.

74

30


are required and must contain valid information."
/>

31


<webuijsf:label

binding =
"#{Validation.nameLabel}"

for =

32


"nameTextField"

id =
"nameLabel"

style =
"left: 24px;

33


to
p: 75px; position: absolute"

text =
"Name:"
/>

34


<webuijsf:textField

binding =
"#{Validation.nameTextField}"

35


id =
"nameTextField"

required =
"true"

style =
"left:

36

96px; top: 72px; position: ab
solute; width: 216px"

37


validatorExpression =


38



"#{Validation.nameLengthValidator.validate}"

39


valueChangeListenerExpression =

40


"#{Validation.name
TextField_processValueChange}"
/>

41


<webuijsf:message

binding =
"#{Validation.nameMessage}"


42


for =
"nameTextField"

id =
"nameMessage"

showDetail =

43


"false"

showSummary =
"true"


44



style =
"left: 336px; top: 74px; position: absolute"
/>

45


<webuijsf:label

binding =
"#{Validation.emailLabel}"

for =

46


"emailTextField"

id =
"emailLabel"

style =
"left: 24px;

47


top: 109px
; position: absolute"
text =
"E
-
Mail:"
/>

48


<webuijsf:textField

binding =

49


"#{Validation.emailTextField}"

id =
"emailTextField"


50


required =
"true"

style =
"left: 96px; top: 106px;

51



position: absolute; width: 216px"

validatorExpression =


52


"#{Validation.emailTextField_validate}"
/>

53


<webuijsf:message

binding =
"#{Validation.emailMessage}"


54


for =
"emailTextField"

id =
"emailMessage"

showDetail =

55


"false"

showSummary =
"true"

style =
"left: 336px; top:

56


108px; position: absolute"
/>

57


<webuijsf:label

binding =
"#{Validation.phoneLabel}"

for =

58



"phoneTextField"

id =
"phoneLabel"

style =
"left: 24px;


Outline

Validation.jsp


(2 of 6 )


Specifies the
validator for the
name
Text Field

Specifies the
validator for the
email
Text Field



2007 Pearson Education,
Inc. All rights reserved.

75

59


top: 143px; position: absolute"

text =
"Phone:"
/>

60


<webuijsf:textField

binding =

61


"#{Validation.phoneTextField}"

id =
"phoneTextField"


62


required =
"true"

style =
"left:
96px; top: 140px;

63


position: absolute; width: 216px"
validatorExpression =


64


"#{Validation.phoneTextField_validate}"
/>

65


<webuijsf:message

binding =
"#{Validation.phoneMessage}"


66



for =
"phoneTextField"

id =
"phoneMessage"

showDetail =

67


"false"

showSummary =
"true"

style =
"left: 336px; top:

68


142px; position: absolute"
/>

69


<webuijsf:button

actionExpression =


70


"#{Validation.submitButton_action}"

binding =


71


"#{Validation.submitButton}"

id =
"submitButton"

style =

72


"left: 23px; top: 192px; position: absolute; width:

73


100px"

text =
"Submit"
/>

74


<webuijsf:staticText

binding =
"#{Validation.resultText}"


75


escape =
"false"

id =
"resultText"

rendered =
"false"

76


style =
"left: 24px; top: 216px; position: absolute"

77


text =
"Thank you for your submission.&lt;br/&gt;We

78


received the following information:"
/>

79


<h:panelGrid

binding =
"#{Validation.resultGridPanel}"


80


columns =
"2"

id =
"resu
ltGridPanel"

rendered =
"false"

81


style =
"border
-
width: 1px; border
-
style: solid;

82


background
-
color: #ffff99; height: 96px; left: 24px;

83


top: 264px; position: absolute"

width =
"288"
>

84


<webuijsf:staticText

binding =

85


"#{Validation.nameResultLabel}"


86


id =
"nameResultLabel"

text =
"Name:"
/>

87


<webuijsf:staticText

binding =

88



"#{Validation.nameResult}"

id =
"nameResult"
/>


Outline

Validation.jsp


(3 of 6 )


Specifies the
validator for the
phone number
Text Field



2007 Pearson Education,
Inc. All rights reserved.

76

89


<webuijsf:staticText

binding =

90


"#{Validation.emailResultLabel}"


91


id =
"emailResultLabel"

text =
"E
-
Mail:"
/>

92


<webuijsf:staticText

binding =

93



"#{Validation.emailResult}"

id =
"emailResult"
/>

94


<webuijsf:staticText

binding =

95


"#{Validation.phoneResultLabel}"


96


id =
"phoneResultLabel"

text =
"Phone:"
/>

97



<webuijsf:staticText

binding =

98


"#{Validation.phoneResult}"

id =
"phoneResult"
/>

99

</h:panelGrid>

100

</webuijsf:form>

101

</webuijsf:body>

102

</webuijsf:html>

103


</webuijsf:page>

104

</f:view>

105

</jsp:root>


Outline

Validation.jsp


(4 of 6 )




2007 Pearson Education,
Inc. All rights reserved.

77



Outline

Validation.jsp


(5 of 6 )




2007 Pearson Education,
Inc. All rights reserved.

78



Outline

Validation.jsp


(6 of 6 )




2007 Pearson Education,
Inc. All rights reserved.

79


1

// Fig. 26.16: Validation.java


2

// Validating user input.


3

package
validation;


4



5

import
com.sun.rave.web.ui.appbase.AbstractPageBean;


6

import
com.sun.webui.jsf.component.Body;


7

import
com.sun.webui.jsf.component.Button;


8

import
com
.sun.webui.jsf.component.Form;


9

import
com.sun.webui.jsf.component.Head;

10

import
com.sun.webui.jsf.component.Html;

11

import
com.sun.webui.jsf.component.Label;

12

import
com.sun.webui.jsf.component.Link;

13

import
com.sun.webui.jsf.component.M
essage;

14

import
com.sun.webui.jsf.component.Page;

15

import
com.sun.webui.jsf.component.StaticText;

16

import
com.sun.webui.jsf.component.TextField;

17

import
javax.faces.FacesException;

18

import
javax.faces.application.FacesMessage;

19

impo
r
t
javax.faces.component.UIComponent;

20

import
javax.faces.component.html.HtmlPanelGrid;

21

import
javax.faces.context.FacesContext;

22

import
javax.faces.validator.LengthValidator;

23

import
javax.faces.validator.ValidatorException;

24


25

pu
blic clas
s
Validation
extends
AbstractPageBean

26

{

27


private int
__placeholder;

28




Outline

Validation.java


(1 of 3 )




2007 Pearson Education,
Inc. All rights reserved.

80

29


private void
_init()
throws
Exception

30

{

31

nameLengthValidator.setMaximum(
30
);

32

}
// end method _init

33


34


// To save space, we omitted the code in lines 34
-
407. The complet
e

35


// source code is provided with
this chapter's examples.


36


408
// validates entered email address against the regular expression

409

// that represents the form of a valid email address.

410


public void
emailTextField_validate( FacesContext context,

411


UIComponent component, Object value )

412

{

413

String email = String.valueOf( value );

414



415


// if entered email address is not in a valid forma
t

416


if
( !email.matches(



417



"
\
\
w+([
-
+.']
\
\
w+)*@
\
\
w+([
-
.]
\
\
w+)*
\
\
.
\
\
w+([
-
.]
\
\
w+)*"
) )


418


{


419



throw

new

ValidatorException(

new

FacesMessage(



420



"Enter a va
lid email address, e.g. user@domain.com"

) );

421


}

// end if


422

}
// end method emailTextField_validate

423


424

// validates entered phone number against the regular expression

42
5

// that represents the form of a valid phone number.

426


public void
phoneTextField_validate( FacesContext context,

427

UIComponent component, Object value )

428

{

429

String phone = String.valueOf( value );


Outline

Validation.java


(2 of 3 )




2007 Pearson Education,
Inc. All rights reserved.

81

430


431

// if entered phone number is not in a valid format

432


if
( !phone.matches(


433


"((
\
\
(
\
\
d{3}
\
\
) ?)|(
\
\
d{3}
-
))?
\
\
d{3}
-
\
\
d{4}"

) )


434


{




435



throw

new

ValidatorException(

new

FacesMessage(



436



"Enter a valid phone number, e.g. (555) 555
-
1234"

) );

437


}
// end if


438

}
// end method phoneTextField_validate

439


440

// displays the values the user entered

441


public String
submitButton_action()

442

{

443

String name = String.valueOf( nameTextField.getValue() );

444

String email
= String.valueOf( emailTextField.getValue() );

445

String phone = String.valueOf( phoneTextField.getValue() );

446

nameResult.setValue( name );

447

emailResult.setValue( email );

448

phoneResult.setValue( phone );

449


resultGridPanel.setRendered(
true
);

450

resultText.setRendered(
true
);

451


return null
;

452

}
// end method submitButton_action

453

}

// end class Validation


Outline

Validation.java


(3 of 3 )




1992
-
2007 Pearson Education, Inc. All rights reserved.

82

26.5 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.

83

26.5 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.