•
•
TableofContents
Index
coreJavaServer™Faces
ByDAVIDGEARY,CAYHORSTMANN
Publisher :AddisonWesley
PubDate :June15,2004
ISBN :0-13-146305-5
Pages :552
JavaServerFacespromisestobringrapid
user-interfacedevelopmenttoserver-side
Java.Itallowsdeveloperstopainlesslywrite
server-sideapplicationswithoutworrying
aboutthecomplexitiesofdealingwith
browsersandWebservers.Italsoautomates
low-level,boringdetailslikecontrolflowand
movingcodebetweenwebformsand
businesslogic.
JavaServerFaceswasdesignedtosupport
draganddropdevelopmentofserver-side
applications,butyoucanalsothinkofitasa
conceptuallayerontopofservletsand
JavaServerPages(JSP).ExperiencedJSP
developerswillfindthatJavaServerFaces
providesmuchoftheplumbingthatthey
currentlyhavetoimplementbyhand.Ifyou
alreadyuseaserver-sideframeworksuchas
Struts,youwillfindthatJavaServersFaces
usesasimilararchitecture,butismore
flexibleandextensible.JavaServerFacesalso
comeswithserver-sidecomponentsandan
eventmodel,whicharefundamentallysimilar
tothesameconceptsinSwing.
JavaServerFacesisquicklybecomingthe
standardWeb-applicationframework.Core
JavaServerFacesistheonebookyouneedto
masterthispowerfulandtime-saving
technology.
WithoutassumingknowledgeofJSPand
servlets,CoreJavaServerFaces:
showshowtobuildmorerobust
applicationsandavoidtedioushandcoding
answersquestionsmostdevelopersdon't
evenknowtoask
demonstrateshowtouseJSFwithTilesto
buildconsistentuserinterfaces
automatically
provideshints,tips,andexplicit"how-to"
informationthatallowsyoutoquickly
becomemoreproductive
explainshowtointegrateJSFwith
databases,usedirectoryservices,wireless
apps,andWebservices
teachesbestpracticesandgoodhabitslike
usingstylesheetsandmessagebundles
coversalloftheJSFtagsandhowto
createnewtaglibraries
•
•
TableofContents
Index
coreJavaServer™Faces
ByDAVIDGEARY,CAYHORSTMANN
Publisher :AddisonWesley
PubDate :June15,2004
ISBN :0-13-146305-5
Pages :552
Copyright
AboutPrenticeHallProfessionalTechnicalReference
Preface
AboutThisBook
RequiredSoftware
WebSupport
Acknowledgments
Chapter1.GettingStarted
WhyJavaServerFaces
SoftwareInstallation
SampleApplicationAnalysis
JSFFrameworkServices
ASimpleExample
VisualDevelopmentEnvironments
BehindtheScenes
AutomationoftheBuildProcesswithAnt
Chapter2.ManagedBeans
DefinitionofaBean
MessageBundles
ASampleApplication
BackingBeans
ConfiguringBeans
BeanScopes
TheSyntaxofValueBindingExpressions
Chapter3.Navigation
StaticNavigation
DynamicNavigation
AdvancedNavigationIssues
Chapter4.StandardJSFTags
AnOverviewoftheJSFCoreTags
AnOverviewoftheJSFHTMLTags
TextFieldsandTextAreas
SelectionTags
Forms
ButtonsandLinks
Messages
Panels
Chapter5.DataTables
TheDataTableTag
ASimpleTable
HeadersandFooters
EditingTableCells
DatabaseTables
h:dataTableAttributes
JSFComponentsinTableCells
StylesforRowsandColumns
TableModels
ScrollingTechniques
Chapter6.ConversionandValidation
OverviewoftheConversionandValidationProcess
UsingStandardConverters
ProgrammingwithCustomConvertersandValidators
UsingStandardValidators
ImplementingCustomTags
Chapter7.EventHandling
Life-CycleEvents
ValueChangeEvents
ActionEvents
EventListenerTags
ImmediateComponents
PhaseEvents
PuttingItAllTogether
Chapter8.SubviewsandTiles
CommonLayouts
ABookViewerandaLibrary
ContentInclusionintheBookViewer
TheBookViewer
TheLibrary
Chapter9.CustomComponents
ImplementingCustomComponentswithClasses
Encoding:GeneratingMarkup
Decoding:ProcessingRequestValues
RevisitingtheSpinner
ImplementingCustomComponentTags
EncodingJavaScripttoAvoidServerRoundtrips
UsingChildComponentsandFacets
Chapter10.ExternalServices
AccessingaDatabase
UsingLDAPforAuthentication
ManagingConfigurationInformation
UsingWebServices
Chapter11.WirelessClients
RenderingTechnologiesforMobileClients
MIDPBasics
ComponentImplementationforMobileClients
MobileCommunicationandControlFlow
TheBattleshipGame
Chapter12.HowDoI…
WebUserInterfaceDesign
Validation
Programming
DebuggingandLogging
Index
Copyright
©2004SunMicrosystems,Inc.
PrintedintheUnitedStatesofAmerica.
4150NetworkCircle,SantaClara,California
95054U.S.A.
Allrightsreserved.Thisproductandrelateddocumentationare
protectedbycopyrightanddistributedunderlicensesrestricting
itsuse,copying,distribution,anddecompilation.Nopartofthis
productorrelateddocumentationmaybereproducedinany
formbyanymeanswithoutpriorwrittenauthorizationofSun
anditslicensors,ifany.
RESTRICTEDRIGHTSLEGEND:Use,duplication,ordisclosure
bytheUnitedStatesGovernmentissubjecttotherestrictions
setforthinDFARS252.227-7013(c)(1)(ii)andFAR52.227-19.
TheproductsdescribedmaybeprotectedbyoneormoreU.S.
patents,foreignpatents,orpendingapplications.
TRADEMARKSHotJava,Java,JavaDevelopmentKit,J2EE,JPS,
JavaServerPages,EnterpriseJavaBeans,EJB,JDBC,J2SE,
Solaris,SPARC,SunOS,andSunsoftaretrademarksofSun
Microsystems,Inc.Allotherproductsorservicesmentionedin
thisbookarethetrademarksorservicemarksoftheir
respectivecompaniesororganizations.
PrenticeHallPTRoffersexcellentdiscountsonthisbook
whenorderedinquantityforbulkpurchasesorspecial
sales.Formoreinformation,pleasecontactU.S.
CorporateandGovernmentSales,1-800-382-3419,
Forsalesoutsideofthe
U.S.,pleasecontactInternationalSales,1-317-5813793,
AcquisitionsEditor:GregoryG.Doench
EditorialAssistant:RaquelKaplan
ProductionSupervision:PattiGuerrieri
CoverDesignDirector:JerryVotta
CoverDesigner:AnthonyGemmellaro
ArtDirector:GailCocker-Bogusz
ManufacturingManager:AlexisR.Heydt
MarketingManager:ChrisGuzikowski
SunMicrosystemsPressPublisher:MyrnaRivera
FirstPrinting
SunMicrosystemsPress
APrenticeHallTitle
AboutPrenticeHallProfessional
TechnicalReference
Withoriginsreachingbacktotheindustry'sfirstcomputer
sciencepublishingprograminthe1960s,andformallylaunched
asitsownimprintin1986,PrenticeHallProfessionalTechnical
Reference(PHPTR)hasdevelopedintotheleadingproviderof
technicalbooksintheworldtoday.Oureditorsnowpublishover
200booksannually,authoredbyleadersinthefieldsof
computing,engineering,andbusiness.
Ourrootsarefirmlyplantedinthesoilthatgaverisetothe
technicalrevolution.Ourbookshelfcontainsmanyofthe
industry'scomputingandengineeringclassics:Kernighanand
Ritchie'sCProgrammingLanguage,Nemeth'sUNIXSystem
AdministrationHandbook,Horstmann'sCoreJava,and
Johnson'sHigh-SpeedDigitalDesign.
PHPTRacknowledgesitsauspiciousbeginningswhileitlookstothe
futureforinspiration.Wecontinuetoevolveandbreaknewgroundin
publishingbyprovidingtoday'sprofessionalswithtomorrow's
solutions.
Preface
WhenweheardaboutJavaServer™Faces(JSF)atthe2002
JavaOneconference,wewereveryexcited.Bothofushad
extensiveexperiencewithclient-sideJavaprogramming,and
hadlivedtotellthetaleDavidinGraphicJava,andCayinCore
Java,bothpublishedbySunMicrosystemsPress.Whenwefirst
triedwebprogrammingwithservletsandJavaServerPages
(JSP),wefoundittoberatherunintuitiveandtedious.
JavaServerFacespromisedtoputafriendlyfaceinfrontofa
webapplication,allowingprogrammerstothinkabouttext
fieldsandmenusinsteadoffrettingoverpageflipsandrequest
parameters.Eachofusproposedabookprojecttothe
publisher,whopromptlysuggestedthatweshouldjointlywrite
theSunMicrosystemsPressbookonthistechnology.
IttooktheJSFexpertgroup(ofwhichDavidisamember)
anothertwoyearstoreleasetheJSF1.0specificationand
referenceimplementation.Thisreleasefulfillsmanyofthe
originalpromises.Youreallycandesignwebuserinterfacesby
puttingcomponentsonaformandlinkingthemtoJavaobjects,
withouthavingtowriteanycodeatall.Theframeworkwas
designedfortoolsupport,andthefirstbatchofdrag-and-drop
GUIbuildersisnowemerging.Theframeworkisextensibleyou
arenotlimitedtothestandardsetofHTMLcomponents,and
youcanevenusecompletelydifferentrenderingtechnologies,
tosupport,forexample,wirelessdevices.Andfinally,unlike
competingtechnologiesthatletyoutumbledownadeepcliff
onceyoustepbeyondtheglitz,JSFsupportsthehard
stuffseparationofpresentationandbusinesslogic,navigation,
connectionswithexternalservices,andconfiguration
management.
Ofcourse,beinga1.0release,thecurrentversionofJSFisfar
fromperfect.SomeoftheAPIsareawkward.Wesupplyyou
withutilityclassesinthecom.corejsf.utilpackagetoreduce
yourpain.Also,therearefewercomponentsthanweoriginally
expected.WhileJSFhasapowerfulandconvenientdatatable
component,someusefulcomponentssuchastabbedpanes,
scrollers,fileuploads,andsoon,werenotincludedforlackof
time.Inthebook,weshowyouhowtoimplementthese
features.Ofcourse,weexpectthenextreleaseofJSFto
remedymanyoftheseshortcomings.
WearestillexcitedaboutJSF,andwehopeyouwillsharethis
excitementwhenyoulearnhowthistechnologymakesyoua
moreeffectivewebapplicationdeveloper.
AboutThisBook
Thisbookissuitableforwebdeveloperswhosemainfocusis
userinterfacedesign,aswellasforprogrammerswho
implementreusablecomponentsforwebapplications.Thisisin
starkcontrasttotheofficialJSFspecification,adenseand
pompouslywordeddocumentwhoseprincipalaudienceis
frameworkimplementors,aswellaslong-sufferingbook
authors.
Thefirsthalfofthebook,extendingtothemiddleofChapter6,
focusesontheJSFtags.ThesetagsaresimilartoHTMLform
tags.TheyarethebasicbuildingblocksforJSFuserinterfaces.
Noprogrammingisrequiredforuseoftousethetags.Weonly
assumeonlybasicHTMLskillsforwebpagesandstandardJava
programmingforthebusinesslogic.
Thefirstpartofthebookcoversthesetopics:
Settingupyourprogrammingenvironment(Chapter1)
ConnectingJSFtagstoapplicationlogic(Chapter2)
Navigatingbetweenpages(Chapter3)
UsingthestandardJSFtags(Chapters4and5)
Convertingandvalidatinginput(Chapter6)
StartingwiththefinalsectionsofChapter6,webeginJSF
programminginearnest.Youwilllearnhowtoperform
advancedtasks,andhowtoextendtheJSFframework.Here
arethemaintopicsofthesecondpart:
Implementingcustomconvertersandvalidators(Chapter6)
Eventhandling(Chapter7)
Includingcommoncontentamongmultiplepages(Chapter
8)
Implementingcustomcomponents(Chapter9)
Connectingtodatabasesandotherexternalservices
(Chapter10)
Supportingwirelessclients(Chapter11)
Weendthebookwithachapterthataimstoanswercommon
questionsoftheform"HowdoI….?"Weencourageyoutohave
apeekatthatchapterassoonasyoubecomecomfortablewith
thebasicsofJSF.Therearehelpfulnotesondebuggingand
logging,andwealsogiveyouimplementationdetailsand
workingcodeforfeaturesthataremissingfromJSF1.0,such
asfileuploads,popupmenus,andapagercomponentforlong
tables.
JSFisbuiltontopofservletsandJSP,butfromthepointof
viewoftheJSFdeveloper,thesetechnologiesmerelyformthe
low-levelplumbing.Whileitcan'thurttobefamiliarwithother
webtechnologiessuchasservlets,JSP,orStruts,wedonot
assumeanysuchknowledge.
RequiredSoftware
Allsoftwarethatyouneedforthisbookisfreelyavailable.You
needtheJavaSoftwareDevelopmentKitfromSun
Microsystems,aservletcontainersuchasTomcat,and,of
course,aJSFimplementation,suchasSun'sreference
implementation.ThesoftwarerunsidenticallyonLinux,MacOS
X,Solaris,andWindows.Weusedthe1.4.2J2SEandTomcat
5.0.19onbothLinuxandMacOSXtodevelopthecode
examplesinthebook.
Wealsoexpectthatintegratedenvironmentswillbecome
commerciallyavailableinthenearfuture.
WebSupport
Thewebpageforthisbookis.Itcontains
Thesourcecodeforallexamplesinthisbook
Usefulreferencematerialthatwefeltismoreeffectivein
browseableformthaninprint
Alistofknownerrorsinthebookandthecode
Aformforsubmittingcorrectionsandsuggestions
Acknowledgments
Firstandforemost,we'dliketothankGregDoench,oureditor
atPrenticeHall,whohasshepherdedusthroughthisproject,
neverlosinghisnerveinspiteofnumerousdelaysand
complications.ThankstoMaryLouNohrforeditingthe
manuscript,andtoPattiGuerrieriforherproductionwork.We
verymuchappreciateourreviewerswhohavedoneasplendid
job,findingerrorsandsuggestingimprovementsinvarious
draftsofthemanuscript.Theyare:
LarryBrown
FrankCohen,PushToTest
RobGordon,CrookedFurrowFarm
MartyHall,authorofCoreJavaServletsandJavaServer
Pages
JeffMarkham,MarkhamSoftwareCompany
AngusMcIntyre,IBMCorporation
JohnMuchow,authorofCoreJ2ME
SergeiSmirnov,principalarchitectofExadelJSFStudio
RomanSmolgovsky,Flytecomm
StephenStelting,SunMicrosystems,Inc.
ChristopherTaylor,NanshuDensetsu
MichaelYuan,authorofEnterpriseJ2ME
Finally,thankstoourfamiliesandfriendswhohavesupported
usthroughthisprojectandwhoshareourreliefthatitisfinally
completed.
Chapter1.GettingStarted
TopicsinThisChapter
"WhyJavaServerFaces"onpage3
"SoftwareInstallation"onpage4
"ASimpleExample"onpage6
"SampleApplicationAnalysis"onpage12
"VisualDevelopmentEnvironments"onpage21
"JSFFrameworkServices"onpage23
"BehindtheScenes"onpage25
"AutomationoftheBuildProcesswithAnt"onpage30
WhyJavaServerFaces
Judgingfromthejobadvertisementsinemploymentwebsites,
therearecurrentlytwopopulartechniquesfordevelopingweb
applications.
The"rapiddevelopment"style,usingavisualdevelopment
environmentsuchasMicrosoftASP.NET.
The"hard-corecoding"style,writinglotsofcodetosupport
ahigh-performancebackendsuchasJ2EE(theJava2
EnterpriseEdition).
Aswewritethisbook,developmentteamsfaceadifficult
choice.J2EEisanattractiveplatform.Itishighlyscalable.Itis
portabletomultipleplatforms.Itissupportedbymanyvendors.
Ontheotherhand,ASP.NETmakesiteasytocreateattractive
userinterfaceswithouttediousprogramming.Ofcourse,
programmerswantboth:ahigh-performancebackendand
easyuser-interfaceprogramming.
ThepromiseofJavaServerFacesistobringrapiduser-interface
developmenttoserver-sideJava.
Ifyouarefamiliarwithclient-sideJavadevelopment,youcan
thinkofJSFas"Swingforserver-sideapplications."Ifyouhave
experiencewithJavaServerPages(JSP),youwillfindthatJSF
providesmuchoftheplumbingthatJSPdevelopershaveto
implementbyhand.Ifyoualreadyknowaserver-side
frameworksuchasStruts,youwillfindthatJSFusesasimilar
architecture.
NOTE
YouneednotknowanythingaboutSwing,JSP,orStruts
inordertousethisbook.Weassumebasicfamiliarityonly
withJavaandHTML.
JSFhastheseparts:
AsetofprefabricatedUIcomponents
Anevent-drivenprogrammingmodel
Acomponentmodelthatenablesthird-partydevelopersto
supplyadditionalcomponents
JSFcontainsallthenecessarycodeforeventhandlingand
componentorganization.Applicationprogrammerscanbe
blissfullyignorantofthesedetailsandspendtheireffortonthe
applicationlogic.
ForthepromiseofJSFtobefullyrealized,weneedintegrated
developmentenvironmentsthatgenerateJSFapplications.As
wewritethischapter,theseIDEsarejustbeginningtobe
developed.Forthatreason,westartthistutorialchapterby
showingyouhowtocomposeaJSFapplicationbyhand.When
readingtheinstructionsinthischapter,considerthatmanyof
thestepscanandwillbeautomatedinthefuture.
SoftwareInstallation
Youneedthefollowingsoftwarepackagestogetstarted.
TheJavaSDK1.4.1orhigher( />TheTomcatservletcontainer
( />TheJavaServerFacesreferenceimplementation
( />Thesamplecodeforthisbook,availableat
WeassumethatyoualreadyinstalledtheJavaSDKandthat
youarefamiliarwiththeSDKtools.Formoreinformationon
theJavaSDK,seeHorstmann&Cornell,CoreJava,Sun
MicrosystemsPress,2003.
Inthischapter,wedescribehowtouseJSFwithTomcat5.
Tomcatisaservletcontainer:aprogramthatserveswebpages
andexecutesservletsJavaprogramsthatprocesswebrequests.
JavaServerFacesisbuiltontopoftheservlettechnology,but
youneednotknowanythingaboutservletstobuildJSF
applications.
DownloadandunzipTomcat,theJSFreferenceimplementation,
andthesamplecode.Placethemintodirectoriesofyourchoice.
(Asalways,itisbesttoavoidpathnameswithspaces,suchas
c:\ProgramFiles.)
Intherestofthebook,werefertothesedirectoriesastomcat,
jsfandcorejsf-examples.Forexample,ifwereferto
tomcat/conf/server.xml,youwillneedtolookinsidea
directorysuchas/usr/local/jakarta-tomcat-5.0.19/conf
orc:\jakarta-tomcat-5.0.19\conf.
IfyouuseWindows,youcanchooseaWindowsinstallerfor
Tomcatinsteadoftheplatform-independentZIPfile.Download
andexecutetheinstallerprogram.Whenyouarepromptedfor
theinstallationdirectory,wesuggestthatyouusec:\tomcat
insteadofthedefaultlocationinsidethec:\ProgramFiles
directory.
NOTE
YoucanrunJSFapplicationswithanyservletcontainer
thatsupportstheServlet2.3andJSP1.2specifications.
Tokeeptheinstructionssimple,wecoveronlyTomcat5.
Ifyoupreferanotherservletcontainer,simplyfollowthe
standardprocedurefordeployingwebapplicationson
yourserver.
NOTE
YoucanalsoobtainJSFfromothersources,suchasthe
J2EESDK(or
theJavaWebServicesDevelopmentPack
( />However,thesebundlescontainmanyothersoftware
componentsandhavemorecomplexconfigurations.We
suggestthatyoumoveontomoresophisticated
environmentsafterbecomingcomfortablewithTomcat
andtheJSFreferenceimplementation.
Nowyouarereadytogetstarted.Openacommandshelland
startTomcat.OnUnix/Linux,youusethecommand
tomcat/bin/startup.sh
(SeeFigure1-1.)OnWindows,launch
tomcat\bin\startup.bat
Figure1-1.StartingTomcat
Alternatively,ifyouusedtheWindowsinstallertoinstall
Tomcat,youcanusethe"StartTomcat"menuiteminthestart
menu.
TotestthatTomcatrunsproperly,pointyourbrowserto
http://localhost:8080.Youshouldseeawelcomepage(see
Figure1-2).
Figure1-2.TomcatWelcomePage
YoushutdownTomcatwiththecommand
tomcat/bin/shutdown.sh
or,onWindows,