MasteringOmniFaces
Writtenby:AnghelLeonardandConstantinAlin
Reviewedby:BaukeScholtzandArjanTijms
GlasnevinPublishing,2ndFloor,
13UpperBaggotStreet,Dublin4,Ireland
www.glasnevinpublishing.com
Thiseditionpublishedin2015byGlasnevinPublishing
©AnghelLeonardandConstantinAlin2015
All rights reserved. No part of this book may be reproduced or utilised in any form or by any means electronic or
mechanical including photography, filming, recording, video recording, photocopying, or by information storage and
retrievalsystemandshallnot,byanywayoftradeorotherwise,belent,resoldorotherwisecirculatedinanyformof
binding or cover other than that in which it is published without prior permission in writing from the publisher. The
moralrightsoftheauthorhavebeenasserted.
Alltrademarksthatappearinthebookaretrademarksoftheirrespectiveowners.Ratherthanputatrademarksymbol
after every occurrence of a trademarked name, we use names in an editorial fashion only, and to the benefit of the
trademarkowner,withnointentionofinfringementofthetrademark.Wheresuchdesignationsappearinthisbook,they
havebeenprintedwithinitialcaps.
The author and publisher of this book have used their best efforts in preparing this book. These efforts include the
development,researchandtestingofthetheoriesandcomputationalmodelsgiveninthebook.Theauthorandpublisher
make no warranty of any kind, expressed or implied, with regard to any text, models, program code or algorithms
containedinthisbook.Theauthorandpublishershallnotbeliableinanyeventforincidentalorconsequentialdamages
in connection with, or arising out of, the furnishing, performance, or use of this text, models, program code or
algorithms.
ISBN:978-1-908689-29-0
ACIPcataloguerecordforthisbookisavailablefromtheBritishLibrary
PapersusedbyGlasnevinPublishingarefromwellmanagedforestsandotherresponsiblesources.
Glasnevin Publishing books are available at special quantity discounts for use in educational courses or for use in
corporatetrainingprograms.Formoreinformation,pleaseemail
JavaTMisaregisteredtrademarkofOracleand/oritsaffiliates
Contents
Preface
AbouttheAuthors
AbouttheReviewers
Acknowledgements
Chapter1:OmniFacesComponents
1.1OutputLabel
1.2Param
1.3OutputFormat
1.4Messages
1.5OnloadScript
1.6DeferredScipt
1.7Highlight
1.8ViewParam
1.9FormandIgnoreValidationFailed
1.10Cache
1.11CommandScript
1.12ResolveComponent
1.13ResourceInclude
1.14GraphicImage
1.15ComponentIdParam
1.16MoveComponent
1.17Tree
1.18ConditionalComment
Chapter2:OmniFacesValidators
2.1JsfLabelMessageInterpolator
2.2ValueChangeValidatorandValueChangeConvertor
2.3RequiredCheckboxValidator
2.4.ValidateBean
2.5ValidateUniqueColumn
2.6ValidateXxx
Chapter3:OmniFAcesTagHandlers
3.1Convertor/Validator
3.2ImportConstants/ImportFunctions
3.3ViewParamValidationFailed
3.4EnableRestorableView
3.5MassAttribute
3.6MethodParam
3.7TagAttribute
Chapter4:OmniFacesConvertors
4.1GenericEnumConvertor
4.2SelectItemsConvertorandSelectItemsIndexConvertor
Chapter5:OmniFacesExceptionHandlers
5.1FullAjaxExceptionHandler
5.2FacesMessageExceptionHandler
Chapter6:OmniFacesContexts
6.1OmniPartialViewContext
Chapter7:OmniFacesResourceHandlers
7.1CDNResourceHandler
7.2UnmappedResourceHandler
7.3CombinedResourceHandler
Chapter8:OmniFacesEventListeners
8.1.InvokeActionEventListener
8.2ResetInputAjaxActionListener
Chapter9:OmniFacesViewHandlers
9.1NoAutoGeneratedIdViewHandler
Chapter10:There’sMore!
Preface
OmniFaces is a utility library for JSF and a comprehensive compendium of
programmingtechniques,designpatternsandrecipesforJSFdevelopers.
MasteringOmniFaces is targeted towards JSF page authors/developers that wish to use
OmniFacesintheirprojectsandJSFdevelopersinterestedingoingdeepintotheJSFAPI
“bowels”inordertobecomerealJSFmasters.
When confronted with “unusual” JSF tasks (e.g. fixing bugs, solve gaps, avoiding
pitfalls,etc.)weoftendon’thaveenoughselfconfidencethatwearetherightpersonto
completethetask,soweaskforprofessionalhelpindifferentcommunitiesor“question
and answer sites”, such as StackOverflow. StackOverflow isn’t just casually mentioned
here,asitseemsthattheOmniFacesprojectideawas“born”asaprofessionalandunitary
answer to the most popular questions/bugs/gaps reported on this site. The professionals
that picked up those reports from StackOverflow and answered/solved them via the
OmniFacesprojectareBaukeScholtzandArjanTijms.BothScholtzandTijmsareJSF
ExpertGroupmembersdirectlyinvolvedinJSFdevelopment.Theyconstantly“scan”the
JSFworldfornewlyreportedissuesandarealwaysopentoreceivenewideas/suggestions
for improving OmniFaces and JSF. In this way, OmniFaces is always up to date and is
continuouslygettingbetter.Moreover,OmniFacesisavailableundertheApacheLicense
2.0,soitmaybefreelyused,distributed,andmodified.
In this book, we “dissect” OmniFaces 2.1 and we extract valuable lessons that will
definitelygiveyouaboostintheJSFfield.Afteryouhavereadthisbook,youwillsay
Wow,IknewsolittleaboutJSFbefore!Now,I’mabletosolvetasksthatIdidn’thavea
clueaboutinthepast!
Asyouwillsee,however,itisnoteasytoreachahighlevelofJSFknowledge.Not
everything will be easy to understand and assimilate, and many advanced techniques
requirehardwork,patience,creativityandperseverance.Wheneveryouarereallystuckor
youhaveabrilliantideaofhowtoimprovetheOmniFacesproject,justcontactususing
theinformationintheContact/Questionssubsectionbelow.
Whilereadingthisbook,itwouldbegreattoalsofollowthepointedreferences.These
referencescomefrom andtheycoverdifferentJSFfundamentalsthat
couldn’tbecoveredinthebook.Theyaremeanttosupplymandatoryinformationinorder
tounderstandaspecifictopic.Moreover,theOmniFacesutilitiesreferences(alsocovered
on ) are important to understand the OmniFaces shortcuts and to
seriously increase your collection of JSF helpers. For convenience, we have all these
referencescollectedinaZEEFpageavailableat .
Whoisthisbookfor?
MasteringOmniFacesisabookforanyJSFdeveloper.Fromnovicetoexpert,anyJSF
developerwillfindvaluablelessonsandtechniquesmeanttotakeJSFprojectstoahigher
levelofimplementationandrobustness.Fornewcomers,thisbookwillbeagreatguide
that will help them to learn JSF in a “healthy” manner and will answer many specific
novicequestions.ForJSFdevelopers,whohavepreviousJSFexperiencebutarelacking
anunderstandingofbestpracticesandastandardmethodsofimplementingfunctionality,
thisbookwillbelikea“goldmine”.
Whatthisbookcovers
Thebookisdividedintothreepartsandtenchaptersasfollows:
PARTI-thispartcontainsfourchaptersstructuredinsections.Eachsectionisdedicated
to an OmniFaces artifact “dissected” into seven subsections: Theoretical aspects,
Problem/Issue,BrainstormingJSF,OmnifyBrainstorming,HowitWorks,Conclusionand
SectionHighlights.
Chapter1-OmniFacesComponents
Fromthischapteryoucancollectasetofrecipesandtechniquesforwritingavarietyof
customcomponents.Youwilllearnhowtowritefamiliesofcomponents,extendexisting
components, suppressing/adding specific functionalities, writing custom renderers, etc.
Chapter1covers:
Cache
server-sidecacheofrenderedmarkup
CommandScript
generateaJSfunctionintheglobalJSscope
ComponentIdParam
renderjustoneormorecomponentsona
viewviaaGETparameter
ConditionalComment
rendersaconditionalcomment(specificto
IE)
DeferredScript
defertheloadingofthegivenscriptresource
tothewindowloadevent
Form
keepvieworrequestparametersinthe
requestURLafterapost-back
IgnoreValidationFailed
ignorevalidationfailures(invokeaction
phasewillbeexecutedanyway)
GraphicImage
loadimagesfrom byte[] / InputStream /SVG
(optionalasdataURI)
Highlight
highlightsallinvalid UIInput componentsand
theassociatedlabels
Messages
multiple for ,singlemessage,HTML
escaping,Iterationmarkupcontrol
MoveComponent
movecomponents,facetsandbehaviorsat
runtime
OnloadScript
executeitsscriptbodyoneveryAJAX
request
OutputFormat
capturingtheoutputandexposingitintothe
requestscope
OutputLabel
setitsvalueasthelabelofthecomponent
pointedbyits for attribute
Param
supporta Converter toconvertthesupplied
valuetostring
ResolveComponent
putinFacelet/requestscopeareferencetoa
component
ResourceInclude
catchtheoutputfromaJSP/Servletand
renderittotheJSFwriter
Tree
fullcontroloverthemarkupofatree
hierarchy
ViewParam
stateless <f:viewParam>
Chapter2-OmniFacesValidators
AsaJSFdeveloper,youhaveprobablyusedtheJSFbuilt-invalidatorsandwroteseveral
customvalidatorsconformingtoJSFstandards.Thischapterwilltakeyoutoanotherlevel
of implementing validators. Amongst other things, you will see how to write a message
interpolator, and how to implement cross-field validators, which are not supported by
defaultinJSF.Chapter2covers:
JsfLabelMessageInterpolator
alabelcanappearinthemiddleofa
beanvalidationmessage
RequiredCheckboxValidator
solverequired=“true” attributeand
UISelectBoolean issue
ValueChangeValidator
validateonlywhenthesubmittedvalue
isreallychanged
validateAll
validatesifALLUIInput shavebeen
filledout
validateAllOrNone
validatesifALL/NONEUIInput shave
beenfilledout
validateEqual
validatesifALL UIInput shavethesame
value
validateMultiple
validatemultiplefieldsbyeithera
customvalidatormethod
validateOne
validatesifONLYONE UIInput have
beenfilledout
validateOneOrMore
validatesifatleastONE UIInput hasbeen
filledout
validateOneOrNone
validatesifONLYONE/NONE UIInput
hasbeenfilledout
validateOrder
validatesifthe UIInput svaluesrespecta
specifiedorder
validateUnique
validatesifALL UIInput shaveanunique
value
validateUniqueColumn
validatesifthe UIInput valueinan UIData
isuniqueinallrows
validateBean
beanvalidationonaperUICommand / UIInput componentbasis,as
wellasvalidatingagivenbeanatthe
classlevel
Chapter3-OmniFacesTagHandlers
WhenaJSFdeveloperwriteshisfirstclassicaltaghandler,wecansaythathehasreached
a “decent” level of JSF knowledge. It is a well-known fact that tag handlers are a
milestoneinaJSFdeveloper’sevolution.TheOmniFacestaghandlersaremeantto“blow
yourmind”and,toparaphraseafamousTVserial,to“boldlygowherenomanhasgone
before”.Chapter3covers:
converter
supportfordeferredvalueexpressionsin
allconverterattributes
enableRestorableView
recreatetheentireviewwheneverthe
viewhasbeenexpired
ignoreValidationFailed
ignorevalidationfailureswhen
executingan UICommand action
importConstants
mapconstantsofthegivenFQNofa
typeintherequestscope
importFunctions
mapfunctionsofthegivenFQNofa
typeinthe“Faceletscope”
massAttribute
setsanattributeofthegivennameand
valueonallnestedcomponents
methodParam
passamethodexpressionasattribute
intoaFaceletstag
tagAttribute
explicitlydeclareatagattributeona
Faceletstagfile
validator
supportfordeferredvalueexpressionsin
allvalidatorattributes
viewParamValidationFailed
handleviewparametervalidationfailure
viaredirectorHTTPerrorcode
Chapter4-OmniFacesConverters
OmniFacesrevealsseveraladvancedconverterswhichsolvesomeJSFgapsthatcontinue
topersistoverJSFmilestonereleases.Chapter4covers:
ListIndexConverter
convertsbasedontheposition(index)of
theselectediteminthelist
ListConverter
workdirectlyviaa List of
entities(cannotuse ListIndexConverter )
SelectItemsConverter
automativallyconvert <f:selectItems>
entities
SelectItemsIndexConverter
asSelectItemsConverter, butconvertsbased
ontheposition(index)
ValueChangeConverter
convertonlywhenthesubmittedvalue
haschanged
GenericEnumConverter
usein UISelectMany componentswhose
valueisbeenboundtoa List<E> property
where E isanenum
PARTII-thispartcontainsfourchaptersstructuredinsections.Eachsectionisdedicated
toanOmniFacesartifact“dissected”infoursubsections:BriefOverview,HowitWorks,
ConclusionandSectionHighlights.
Chapter5-OmniFacesExceptionHandlers
Asyouprobablyknow,treatingexceptionsthatoccurduringAJAXrequestsisarealissue
in JSF. OmniFaces provides a powerful exception handler especially for capturing and
treatingsuch“silent”exceptionsinafriendlymanner.Chapter5covers:
FacesMessageExceptionHandler
addeveryexceptionasa
global FATAL facesmessage
FullAjaxExceptionHandler
handleexceptionsduringAJAX
requestsasnon-AJAXones
Chapter6-OmniFacesContexts
Think about how many times you have written a JSF custom context or a JSF custom
partial view context? If these questions sound interesting to you, then is time to jump
“faster than a cheetah with a jetpack” to OmniPartialViewContext implementation. Chapter 6
covers:
OmniPartialViewContext
extends and improves the standard
partialviewcontext
Chapter7-OmniFacesResourceHandlers
JSF resource handlers are definitely not exploited at full capacity by JSF developers. It
istrue that after we learn about the JSF /resources contract and understand a few aspects
about JSF resources loading and caching, we have that warm fuzzy feeling that we are
pretty good with resource handlers. But, how about loading resources from a CDN
repository,combiningresourcesinasinglerequestorusingunmappedresources?So,read
chapter7andthinkagain!Chapter7covers:
CDNResourceHandler
provide CDN URLs instead of the
defaultlocalURLsforJSFresources
CombinedResourceHandler
create a combined resource for all
scriptsandoneforallstylesheets
UnmappedResourceHandler
map JSF resources on an URL pattern
of /javax.faces.resource/*
Chapter8-OmniFacesEventListeners
UnderstandingJSFeventlistenersisamandatoryskillinaJSFdeveloper’sarsenal.This
chapter will really help you to get the missing puzzle pieces of how event listeners are
working.Forexample,ifyouneversawaJSFartifactthatcanactasanactionlisteneror
asaphaselistener,dependingonhowitisconfiguredintheapplication,thenthischapter
isforyou.Chapter9covers:
InvokeActionEventListener
new <f:event> types preInvokeAction / postInvokeAction
ResetInputAjaxActionListener
resetinputfieldswhicharenotexecuted
duringAJAXsubmit,butwhichare
rendered/updatedduringAJAXresponse
Chapter9-OmniFacesViewHandlers
HavingsolidknowledgeaboutJSFviewhandlersislikehavingaprofessionalmulti-tool,
because through a view handler you can handle the processes that involves the current
view, like initializing, restoring, rendering, etc. Contrary to its many usages, JSF
developersareprettyreservedinwritingcustomviewhandlersortheywritethemforthe
wrong purposes, like dealing with components. OmniFaces provides a really useful and
correctusecase.Chapter9covers:
NoAutoGeneratedIdViewHandler
doesn’tallowauto-generatedIDs
( j_id... )
PARTIII - this part presents a brief overview of the OmniFaces artifacts that were not
presented in detail in this book. The final words are dedicated to the upcoming JSF 2.3
andOmniFaces3.0releases.
Chapter10-There’smore
CDI,FacesViews,Filters,ManagedBeans,RenderKits,Scripts,Functions
Whatyouneedforthisbook
The source code in this book comes as Maven projects developed via NetBeans and
EclipseIDEs.Fortestingthesourcecodeofthisbookyouwillneed:
NetBeans(recommended8.0)/Eclipse(recommendedEclipseMars)
WildFly(recommended8.2)/GlassFish(recommended4.1)
JSF2.2(recommendedlatestversionofMojarraorApacheMyFaces)
OmniFaces2.1or2.2(addedviaPOMfile)
occasionally:PrimeFaces(recommended5.0,addedviaPOMfile),HTTPClient
(recommended4.3.6,addedviaPOMfile)
CustomerSupport
Beside the book content, we offer you several things that will help you to enjoy
OmniFaces,asfollows:
SourceCode
ThesourcecodeforthisbookcanbedownloadedfromthefollowingGitHubrepositories:
-forNetBeansIDE
-forEclipseIDE
IsalsoveryimportanttokeepinmindtheOmniFacesShowcase,whichisarichresource
ofpracticalexamplesforOmniFacesartifactsandisavailableat:
/>
OmniFacesUtilitiesReference
OmniFacescomeswithaconsiderablenumberofutilities(helper)methodswhichsimply
cannotbedescribedinthebook.Eachofthesemethods,however,isexemplifiedonJSF
&OmniFacesFansblog,at: . Thiscanbeaccessedeasilyviathetop
menuoftheblog:
Ifyoufindthismenuhardtofollow/use,youcanalsochecktheZEEFpage,OmniFaces
Utilities, .
OtherReferences
IsveryimportanttounderstandtheJSFfundamentalswhichrepresentthe“bricks”used
by OmniFaces to build new artifacts. Instead of exploring the Internet by yourself (of
course,youarefreetodoso),wetriedtohelpyouwithaunitaryresourceofarticlesand
postsonJSF&OmniFacesFansblog,at: .TheyarealllistedonZEEF
page, ,andmentionedinthebookatspecifictopics.
Youalsomaywanttocheck: />
KeepInformationaboutOmniFacesEvolution
You can always keep informed about OmniFaces evolution on the OmniFaces website,
wikipediapage,andrecentcommitsat:
/> /> />
Contact/Questions
Foranyrelatedquestion,youcancontacttheauthorsat:
/>
IfyouhavespecificprogrammingproblemsorquestionsrelatedtotheOmniFaceslibrary,
feelfreetopostaquestiononStackOverflowusingatleastthe jsf and omnifaces tags.Ifyou
have found bugs or have new ideas, feel free to open a new issue. If you have general
feedback that’s not either a question, bug report or feature request, or if you have a
review/rating,pleasefeelfreetoleaveitat Devrates or Ohloh .
Ifyouneedtocontactthebookpublisher: