Sie sind auf Seite 1von 32

Introduction to

Java Server Faces


JavaServerFaces
Struts Struts
WingS WingS
WebWork WebWork
Maverick Maverick
Spring Spring
Tapestry Tapestry
WebObjects WebObjects
Echo Echo
Web Tier Frameworks
Frameworks, frameworks, frameworks
JavaServerFacesisaframeworkfor
developingwebbasedUIsinJava.
Frameworksareextremelycommonthese
days,andforagoodreason:
theyhelpmakewebdevelopmenteasier.
JSFenforcesacleanseparationof
presentationandbusinesslogic.
ItfocusesmoreontheUIsideofthingsand
canbeintegratedwithotherframeworks,
likeStruts.
What is Java Server Faces?
JSFisawebapplicationframeworkthat
accomplishestheMVCparadigm

Providessetofreusablecustom
components.

ProvidessetofJSPtagstoaccessthose
components.

4
Java Server Faces
AJavawebapplicationframework
AsetofUIcomponents(representhtmlentities)
APIsto
representcomponents,
managestate,
handleevents,
validateinput,etc.
CustomtaglibrariestoputJSFinaJSP
Statemanagementandevenmodel
BackingBeans(managedbeans)
ExpressionLanguage(EL)

Servletbased,normallyusesJSPs
JSF Benefits
JSFhelpswebapplicationdeveloperstocreateuser
interfaces(UIs):
MakesiteasytoconstructaUIfromasetofreusable
UIcomponents
Simplifiesmigrationofapplicationdatatoandfrom
theUI
HelpsmanageUIstateacrossserverrequests
Providesasimplemodelforwiringclientgenerated
eventstoserversideapplicationcode
Allowswiringclientgeneratedeventstoserverside
applicationcode
JSF
TheprimarydesignpatternofJSFisthe
ModelViewController(MVC)pattern.
JSPwasdesignedtomaketheview
componentofawebapplicationeasyto
createandmanage.
JSFbringsacomponentbasedmodelto
webapplicationdevelopment
Similartothemodelusedinstandalone
GUIapplications
JSF Applications
JavaServerFacesapplicationsaresimilartoany
otherJavawebapplication.
Theyruninaservletcontainer,andtheytypically
containthefollowing:
JavaBeanscomponentscontainingapplicationspecific
functionalityanddata
Eventlisteners
Pages,suchasJSPpages
Serversidehelperclasses,suchasdatabaseaccess
beans

JSF Component Model


Coversawiderangecomponents.
Reusable
Customizable
Stateaware
Easytopluginthirdpartycomponents.
Easytocreatecustomcomponentsofyour
own.
Renderersbringsabstraction
Simple Example: HtmlInputText
Declaredas;
<h:inputTextid=id1value=xxx/>
Givestheoutput
<inputtype=textid=parentformid:id1
value=xxx/>
Customizationattributeslike;
Styleclass
Javascriptevents(onmousoveretc...)
JSF Architecture
JSFfollowsMVCframework

Model:objectsandpropertiesofapplication

View:Rendererstakecareofview.

Controller:FacesServlet/JSFinfrastructure
definestheflowoftheapplication.

11
Theory vs. Practice
12
In theory
Webapplicationsthatworkmorelikedesktopapps
Easiertoprogram
Lessconcernaboutrequestcycle
Betterscopingandseparation
Application/Session/Request
ComponentbindingsfromUItomodel
Abstract component tree that is independent of the
target(HTML,etc.)
Goodseparationofthelogicandpresentation
13
In practice
Hardertoworkwiththantheaverageweb
applicationframework
Biglearningcurve
Havetounderstandtherequestcyclewell
EspeciallythewaysJSFmayshortcircuitit
Preventsyoufromaccessinghalfthecapabilityof
HTML
Abstractiondoneviacustomtaglibswhichmakethe
templatesintoJSFXML
Logicintemplateandcustomtagsdefeatthegoalof
separationofUIandlogic
14
In practice
JSFeventmodelintroducestheneedfor
wrapperstoactuallydealwithmodel
Mustkeepthecomponenttreeandevent
modelinsession

15
JSF structure and code
16
JSF templates
Thetemplate(mostcommonly
jsp)definestheinterface
Thefacesconfigdefinesthe
navigationandthebacking
beans
Backingbeanshandleaction
processing,navigation
processing,andconnectionsto
thelogic(business)layer
Wrapperbeanwrapsthedata
POJOsforJSFhandling
Logiclayerbeanscanbe
injectedasdefinedinthefaces
config
ModelisbasicdataPOJO
17
Template
(jsp)
Backing Bean
(java)
Logic Layer
(rest of app)
faces-config
(xml)
Wrapper
(java)
model
(java)
JSF templates
JSPfilesmostofthetime
Heavilyreliantontaglibraries(taglibs)
Core(f)basicpagedefinitiontags
Html(h)definesstandardhtmltags
Mustlearnalargesetofrestrictivetaglibs
Difficulttoworkwithsinceitdoesnotlooklikenormalhtml
Evenmoredifficulttowritenewones
LargeuseofEL(expressionlanguage)
Canencouragemixingcodewithhtml
18
Sample template
19
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<f:view>
<html><head><title>Items</title></head><body>
<h:form id="items">
<h:dataTable id="itemlist value="#{JsfBean.allItems} var="entry">
<h:column>
<f:facet name="header">
<h:outputText value=""/>
</f:facet>
<h:selectBooleanCheckbox id="itemSelect" value="#{entry.selected}"
rendered="#{entry.canDelete}"/>
<h:outputText value="" rendered="#{not entry.canDelete}"/>
</h:column>
</h:form>
</body></html>
</f:view>
facesconfig.xml
Definesthebackingbeans
NameusedinELintemplate
Scopecontrolled(request,session,etc.)
Definesnavigationrules
Basedonviews
Wherefrom(view)
Whichoutcome(id)
Wheretogo(view)
Canmatchoutcomesusingwildcards
20
Sample facesconfig
21
<faces-config>
<navigation-rule>
<from-view-id>/jsf/JsfItems.jsp</from-view-id>
<navigation-case>
<from-outcome>newItem</from-outcome>
<to-view-id>/jsf/JsfAddItem.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>*</from-outcome>
<to-view-id>/jsf/JsfItems.jsp</to-view-id>
</navigation-case>
</navigation-rule>

<managed-bean>
<managed-bean-name>JsfBean</managed-bean-name>
<managed-bean-class>org.example.jsf.JsfBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
<managed-property>
<property-name>logic</property-name>
<value>#{someLogicBean}</value>
</managed-property>
</managed-bean>
</faces-config>
JSF backing beans
Typicalbeanwithgettersandsettersandadditional
methodstohandleactions
Storedataneededforprocessingtheuseractions
usingsetters
Retrievedatausinggettersandmethods
Processactionsusingmethods
Oftenincludescodetowrapdataobjects
Connectstotherestoftheapplication
Typicallyviainjection
Nonrecursive(i.e.notlikeSpring),willnotinstantiate
dependenciesofdependencies
22
Sample backing bean
23
public class JsfBean {
private DataModel itemsModel;
private JsfItemWrapper currentItem = null;
...
private JsfLogic logic;
public void setLogic(JsfLogic logic) {
this.logic = logic;
}
...
public DataModel getAllItems() {
List wrappedItems = new ArrayList();
List items = logic.getAllVisibleItems(logic.getCurrentSiteId());
for (Iterator iter = items.iterator(); iter.hasNext(); ) {
JsfItemWrapper wrapper =
new JsfItemWrapper((Item) iter.next());
wrappedItems.add(wrapper);
}
itemsModel = new ListDataModel(wrappedItems);
return itemsModel;
}
...
public String processActionList() {
return "listItems";
}
}
JSF wrapper bean
WrapsbasicdataPOJO
RequiredtoavoidputtingUIinformationinthe
dataPOJO
OftenincludesbasicsettersandgettersfortheUI
relatedproperties
Canbemethodsaswell
AlsoincludesasetterandgetterforthedataPOJO
24
Sample wrapper bean
25
public class JsfItemWrapper {
private Item item;
private boolean isSelected; // is this item selected by the user

public JsfItemWrapper(Item item) {
this.item = item;
}
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean isSelected) {
this.isSelected = isSelected;
}
}
Major JSF Concepts
Components
Renderers
Managedbeans
Converters/Validators
Controller(navigationmodel)
Eventhandling
Requestlifecycle
JSF Components
Separatebusinesslogicfrompresentation
Everyviewiscomposedofacomponenthierarchy
Componentscanbeaddedtoviewprogrammaticallyor
viatemplate(JSPbydefault,Faceletsforsuperior
performanceandeaseofdevelopment)
Standardcomponentsdividedintotwogroups:
FacesCore<f:view>,<f:loadBundle>
HTMLwrappers<h:dataTable>,<h:selectMany>,etc.
Component=class+[renderer]+taghandler(JSP)
JSF Renderers
Componentrendererencodes(generatestheHTML)forthe
component
Rendereralsodecodes(setscomponentvaluesfromURLquery
stringandformvars)
Renderersaregroupedintorenderkits
DefaultrenderkitisHTML
Providedeviceindependencew/ochangingthetemplatinglanguage
orcomponentsthemselves
Backing beans
SpecializedJavaBeansthatcollectvaluesfromUIcomponentsand
implementeventlistenermethods
JSFallowsyoutodeclarativelyassociatebackingbeanswithUI
components.
withmarkupinsteadofcode
YouassociateacomponentwithabackingbeanviatheJSF
expressionlanguage
SimilartotheJSTLEL

Backing Beans
<h:outputTextid="helloBeanOutput
value="#{helloBean.numControls}"/>
hooksupanHtmlOutputTextcomponentsvaluedirectlytothe
numControlspropertyofanobjectcalledhelloBean.

Managed Beans
JSFprovidesadeclarativemechanismcalledtheManagedBean
Creationfacilitytoallowthecreationofbackingbeans
<managedbean>
<managedbeanname>helloBean</managedbeanname>
<managedbeanclass>com.virtua.jsf.sample.hello.HelloBean
</managedbeanclass>
<managedbeanscope>session</managedbeanscope>
</managedbean>
ThistellsJSFtocreateaninstanceoftheHelloBeanclasscalled
helloBean,andstoreitintheuserssession.
Thislittlesnippetisallthatsrequiredtomakeanobjectavailable
forintegrationwithUIcomponents.
Anyobjectsthatusethisfacilityarecalledmanagedbeans.
JSF Managed Beans
Linkviewtothemodel(likecontroller)
Provideeventhandlermethodswhichinturncallappropriatemodel
code(save,new)
Providehelpermethods(getAvailableSelectItems)
Holdreferencestooneormoredomainobjects
ManagedbytheframeworkinApplication,Session,Request,or
noscope
Caninjectreferencestorelatedbeansfornestedflows
JSF Value Binding
Componentvaluesbindtomodelbeans
Foreachrequest,theframework
Convertseachinputvalue(String)intotheunderlyingJavatype
(MoneyAmount)
Onoutput,convertsunderlyingJavatypetoString
Youregisterconvertersforcustomtypes
Allsecurityvalidationthereforehandledcentrallyand
automaticallybymodeltype
JSF Value Binding Example
view.xhtml
In logger object
JSF Value Binding Example
Managed beans are registered in faces-config.xml
view.xhtml
JSF Converters / Validators
Convertersarebidirectional
Inputconverter:getAsObject()
Outputconverter:getAsString()
ValidatorsworkwithObjects,notjustStrings
JSFsuppliesstandardconvertersfordate/time,numbers,etc.
Youwritecustomconvertersforrichtypesorspecialbehavior
Converter
Convertsacomponentsvaluetoandfroma
stringfordisplay
AUIcomponentcanbeassociatedwitha
converter
JSFshipswithconvertersforcommontypeslike
datesandnumbers
Convertersalsohandleformattingand
localization.
<h:outputTextvalue="#{user.dateOfBirth}">
<f:convert_datetimetype="both"dateStyle="full"/>
</h:outputText>
JSF Converters / Validators
JSF Converter Example
Converter is registered in faces-config.xml, so all
ValuedTypesafeEnum properties of any bean will use this converter
Validators also registered in faces-config.xml, but not by class
Events and listeners
JSFusestheJavaBeansevent/listenermodel
(alsousedbySwing).
UIcomponentsgenerateevents,and
listenerscanberegisteredtohandlethose
events.
InaJSFapplication,Integratingapplication
logicisamatterofassigningtheappropriate
listenerstocomponentsthatgenerate
eventsthatthelistenersunderstand.

Events and listeners


Therearefourstandardevents:
Valuechangeevents
Actionevents
Datamodelevents
Firedwhenadataawarecomponentselects
arowforprocessing
Phaseevents
ExecutewhileJSFprocessesanHTTP
request
ValueChange Events
Valuechangeeventsaregeneratedbyinputcontrols
whentheuserentersanewvalueintoaninput
component.

ValuechangelistenershandleValuechangeevents
<h:inputText
valueChangeListener="#{myForm.processValueChanged}"/>

Whenauserchangesthetextinthecontroland
submitstheform,JSFwillgenerateavaluechange
event
publicvoidprocessValueChanged(ValueChangeEventevent){
HtmlInputTextsender=(HtmlInputText)event.getComponent();
sender.setReadonly(true);
}
Action events
Generatedwhenauseractivatesa
commandcomponent
Componentsthatgenerateactionevents,
alsocalledactionsources,includecontrols
suchasbuttonsorhyperlinks
Actioneventsarehandledbyaction
listeners
ActionListenersmayormaynotaffect
navigation
Action Listeners
Actionlistenersthataffectnavigationtypically
performsomeprocessingandthenreturna
logicaloutcomethatisusedbyJSFsnavigation
systemtoselectthenextpage
Listenersthatdontaffectnavigationusually
manipulatecomponentsinthecurrentview,or
performsomeprocessingthatchangesmodel
object,butdoesntalterthecurrentpagethe
userisaccessing.
thepageisusuallyredisplayedafterthelistener
finishesexecuting.
Action Listeners
Technically,allnavigationishandledbyasingle
actionlistener.
Thislistenerautomaticallyhandlesanyaction
eventsfiredbyacomponent,soitdoesntneed
toberegisteredmanually.
Bydefault,thisactionlistenerdelegatesallofits
worktoactionmethodsinyourbackingbeans,
soyoucanhavedifferentactionmethodshandle
differentpartsofyourapplication.

Action Methods
<h:commandButtontype="submit"value="Login
action="#{loginForm.login}"/>
Whenauserclicksonthisbutton,anactioneventisfired,anda
methodloginintheloginFormbeanisexecuted
publicclassLoginForm{
...
publicStringlogin(){
if(...){//loginissuccessful
return"success";}
else{return"failure";}}
...
}
Thecontrolwouldbeforwardedbasedonthereturn
string
Action Listener Methods
publicvoiddoIt(ActionEventevent){
HtmlCommandButtonbutton=
(HtmlCommandButton)event.getComponent();
button.setValue("It'sdone!");
}

JSF Controller
Statefulorstatelessnavigationmodel
Frameworkselectsnextviewbasedon
Previousview
Outcomeoftheeventhandler
Eventitself(regardlessofoutcome)
Anycombinationoftheabove
Possibilities
Universalerrorview(triggeredbyerroroutcome)
Wildcardmatchingpermittedinoutcomes,viewIDs
JSF Event Handling
<h:commandButtonaction=#{ReportCtrl.save}>
Generatesaneventwhenpressed
save()isamethodonamanagedbean
JSFcallsReportController.save()
Canalsodefineactionlistenersassociatedwithother
componentsintheform
Example:AccountSearchonanypagewithouthavingtotellJSF
navigationcontrollerabouteachinstance
CustomActionListenerImplrunsbeforeinvokingmethod
Phase Events
WheneveraJSFapplicationreceivesarequest,itgoesthrough
asixstepprocesscalledtheRequestProcessingLifecycle.


May skip to
render phase
or abort request
JSF Request Lifecycle
Restore
View
Apply Request
Values
Process
Validations
Update
Model
Invoke
Application
Render
Response
Request
Response
Retrieve component tree
from client or session
Decode components
(populate w/ String values)
Convert Strings to Objects
Validate Objects
Invoke bean method(s)
Compute navigation
Call setters
on managed beans
Call bean getters to
populate components
JSF Extension Points
Customcomponents
Phaselisteners(before,afteranyphase)
Customconverters/validators
Customrenderers
CustionActionListenerImpltohandleevent
Decorateorreplaceviewhandler,navigationhandler,state
manager,etc.
Web app basics
4keythingsyouneedtodoinawebapp

1. Outputdynamictext
Renderdatatothescreen
2. Loopstructures
Outputcollectionorrendertables
3. Optionalrenderingofcomponents
Rendersomecomponentsbasedonstate
4. TriggerActions
Useractionsordatatransmission
53
Output dynamic text
Usestheh:outputTexttag
Alsoh:outputLabelandh:outputFormat
UsesExpressionLanguage
Requiresabean
Definedinthefacesconfigorthetemplate
Cansetstyleandturnon/offescaping
54
<h:outputText value="#{JsfAppBean.currentItem.title}"/>
<h:outputText value="#{msgs.jsfapp_text}"/>
Loop structure
h:dataTableisthemainloopstructure
Alsoh:panelGridtoadegree
Takesacollectionasvalue
Usesavariable(entry)tointeractwithcollection
Usesh:columntodefineeachcolumn
55
<h:dataTable id="itemlist value="#{JsfAppBean.allItems} var="entry">
<h:column>
<f:facet name="header">
<h:outputText value="#{msgs.jsfapp_text}"/>
</f:facet>
<h:outputText value="#{entry.item.title}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="#{msgs.jsfapp_hidden}"/>
</f:facet>
<h:selectBooleanCheckbox id="itemHidden" value="#{entry.item.hidden}"
disabled="true" />
</h:column>
</h:dataTable>
Optional rendering
Handledperh:tagwiththerenderedattribute(whichtakesEL)
Canprefixwithnottoinvert
Bringsrenderlogicintothetemplate
56
<h:outputText value="#{entry.item.title}"
rendered="#{not entry.canDelete}"/>
<h:commandLink id="updatelink"
action="#{JsfAppBean.processActionUpdate}"
rendered="#{entry.canDelete}">
<h:outputText value="#{entry.item.title}"/>
</h:commandLink>
Trigger actions
Effectivelybindsabeanactiontoasubmitbutton
(h:commandButton)
Alsoh:commandLink
Triggersanactioninthebeanwhichreturnsastring
toindicatestheviewtonavigateto
57
<h:commandButton value="#{msgs.jsfapp_new}"
action="#{JsfAppBean.processActionNew}" />
public String processActionNew() {
currentItem = null;
itemText = TEXT_DEFAULT;
itemHidden = HIDDEN_DEFAULT;
return "newItem";
}
JSF in practice
58
JSF experience
JSFhasasteeplearningcurve
Tendstodothingsinanonintuitiveway
UIcomponentsarerestrictive
Notenoughofthem,notflexibleenough
VeryhardtomakeAJAXwork
Thismaybechanging
UsesJavascripttooheavily
URLlocationiswrong,nobackbutton
VeryhardforUIdesignerstoworkwith
59
JSF structure revisit
Thetemplatemixeshtmland
presentationlogic
BadforUIdesigners
Thefacesconfigisdifficultto
maintain(navigationalsointhe
backingbean)
Easytogetoutofsync
SyntaxnotlikeSpring
Backingbeansactuallywork
fairlywell
Oneofthesavinggraces
Wrapperbeanisextraworkto
havetodealwith
Sometimeshavetowrapmultiple
objects
Requiresextracodeinthe
backingbean
60
Template
(jsp)
Backing Bean
(java)
Logic Layer
(rest of app)
faces-config
(xml)
Wrapper
(java)
model
(java)
Apache MyFaces
ApacheimplementationofJSF
http://myfaces.apache.org/
Opensource
BetterthanSunreferenceimplementation
Extrafeatures
Additionalandmoreflexibletaglibs
Tomahawk(h)newandupdatedcomponents
http://myfaces.apache.org/tomahawk/
RecommendedovertheSunRI
61
URL: http://myfaces.apache.org/tomahawk/
Oracle ADF faces
ArobustandrichsetofUIcomponentsthatworkwithJSF
Advancedtables
Dateandcolorpickers
Fileupload
Clientsidevalidators
DesignedtoworkwithOracleJdeveloper
DecentAJAXsupport
62
URL: http://www.oracle.com/technology/products/jdev/htdocs/partners/addins/exchange/jsf/
Other faces
Facelets
https://facelets.dev.java.net/
JSFwithoutJSP(similartotapestry)
StrutsShale
http://shale.apache.org/
FrameworkbasedonJSF,similartostruts
63
Questions

Das könnte Ihnen auch gefallen