Tải bản đầy đủ (.pdf) (193 trang)

Addison wesley XForms XML powered web forms oct 2003 ISBN 0321154991

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1.13 MB, 193 trang )

3.5SelectingfromaRangeofValues
Modernuserinterfacesprovidewidgetssuchasslidersand
rotarydials,forexample,volumecontrols.Suchuserinterface
controlscanbeviewedasaspecialcaseofselectioncontrol
wheretheunderlyingsetofchoiceshasadditionalstructurein
thattheavailablevaluesarewellordered.XFormsdefinesa
genericrangecontrolthatcanbeusedtopickavaluefroma
setofwell-orderedvalues.
Element range returnsasinglevaluefromthesetofavailable
values.AswithotherXFormscontrols,thesetofavailable
valuesisdeclaredintheXFormsmodel.Thus,itismeaningless
tobindcontrol range totypeswhosevaluespaceisnotwell
ordered.Element range acceptsallthecommonattributes
andchildelementsdescribedinSection3.2;inaddition,special
attributesonelement range areusedtotunethepresentation
andinteractionbehavioroftheresultingcontrolseeFigure3.20
foranexampleofavolumecontrolauthoredusingelement
range .

Figure3.20Volumecontrolauthoredusing
element range .
<htmlxmlns=" /><head><title>VolumeControl</title>
<modelxmlns=" />id="sound"schema="units.xsd">
<instance>
<settingsxmlns=" /><volumexsi:type="percentage"/>...
</settings></instance>
</model></head>
<body>


<groupxmlns=" />


appearance="full"step="5">
<label>Volume</label>
<help>...</help><hint>...</hint>
</range></group>
</body></html>

start Optionalattributestartspecifiesthestartvaluetobemadeavailablebythecontrol.
Bydefault,thestartvalueistheminimumpermissiblevalueasdefinedinthemodel.
end Optionalattributeendspecifiesthemaximumvaluetobemadeavailablebythis
control.Bydefault,theendvalueisthemaximumpermissiblevalueasdefinedin
themodel.
step Attributestepdeterminestheoffsetusedwhenmovingthroughthesetofavailable
values.Ifspecified,itshouldbeappropriateforexpressingthedifferencebetween
twovalidvaluesfromtheunderlyingsetofvalues.Asanexample,whenpicking
fromanorderedsetofnumbers,forexample,whensettingthevolume,specifying
step=5wouldchangethevolumeinstepsof5.

NoticethatthevolumecontrolshowninFigure3.20usesthe
minimumandmaximumpermissiblevaluesdefinedinthe
modelratherthanfurtherconstrainingtheseviaattributesstart
andend.Attributestepspecifiesthatthevolumeshouldbe
changedinstepsof5.Attributeappearanceissettofullto
requestthatthecontrolbepresentedwiththefullrangeof
availablevalues;asaresult,avisualinterfacemightpresent
thiscontrolasasliderthatshowsboththeminimumand
maximumacceptablevaluesseeFigure3.21.

Figure3.21.Visualrenderingofavolumecontrol
createdusing range .



Incontrast,specifyingavalueofminimalforattribute
appearancemightresultinapresentationthattakesupless
displayrealestate.
Specializedwidgetssuchasrotarycontrolsorspindialsmight
berequestedbyspecifyinganamespacequalifiedvaluesuchas

appearance="my:dial".
Thisissimilartorequestingacustomdatepickerasillustrated
inSection3.3.Noticethatthisdesignpermitstheauthorto
createuserinterfacesthatdegradegracefully,thatis,the
controlcanbepresentedasaspindialonadevicethatmakes
suchawidgetavailable;however,theinterfaceisstillusableon
adevicethatdoesnotcontainaspindialwidget.Alternatively,
devicesthatcontainaspindialmightchoosetousethat
representationforpresentingallrangecontrols;thisenables
theXFormsauthortocreateuserinterfacesthateventuallyget
deliveredinamannerthatisoptimalforthetargetdevice.


3.2CommonAspectsofXFormsControls
XFormsuserinterfacecontrolsareusedtocollectuserinput.
ThevariousXFormsuserinterfacecontrolsprovideaconsistent
markupinterfacetoeaseauthoring.TheXMLmarkupis
designedtobefamiliartotoday'sHTMLauthors,while
overcomingsomeoftheidiosyncrasiesfoundinHTMLforms.
Thissectionpresentsahigh-leveldesignoverviewbefore
presentingthesyntacticdetailsofthevarioususerinterface
controls.Indoingso,wewillcoverallaspectsofcommon
markupfoundinXFormsuserinterfacecontrols.


3.2.1AnatomyofaUserInterfaceControl
XFormsdefinesasetofabstractuserinterfacecontrolsthat
collectanddisplayuserinput.TheXFormsdesignseparates
theseuserinterfacecontrolsfromthedatathatiscollected
fromtheuser.Abstractuserinterfacecontrolsaredesignedto
capturetheunderlyingintentoftheuserinteraction,rather
thanitsfinalpresentationonanygivendeviceorinanyspecific
modality.ThismakesitpossibletodeliverXFormsapplications
todifferentdevicesandmodalities.Moregenerally,thisdesign
enablesthecreationofeditinginterfacesthatallowtheuserto
viewandmodifyXMLdataanddocuments.Theseparationof
theuserinterfacefromtheunderlyingmodelandthedesignof
thisuserinterfaceasasetofabstractuserinterfacecontrols
resultinallXFormscontrolshavingthefollowingstructure:
Bind

Bindingattributesthatwirecontroltomodel

Metadata

Metadataforgivingfeedbacktotheuser,forexample,labels

Presentation

Hintsusedtoaffecttherenderingofthecontrol


Style


CSS-basedstyling

Shortcuts

Keyboardshortcutsandacceleratorkeys

Navigation

Wherethiscontrolappearsinthenavigationsequence

Behavior

Actionhandlersforcustombehaviors

Theseaspectsareauthoredviaasetofattributesandchild
elementscommontoallXFormsuserinterfacecontrols.These
characteristicsofauserinterfacecontrolcanbegrouped
accordingtotheirfunctionalityaspertainingtothemodel,
presentation,andinteractionbehavior,respectivelyseeFigure
3.1.WesummarizetheseforeasyreferenceinTable3.2.

Figure3.1.AnatomyofanXFormsuserinterface
control.

3.2.2BindingControlstotheModel


XFormsuserinterfacecontrolsareconnectedtotheunderlying
datamodelusingbindingattributes.Attributepair(model,ref)
specifiestheportionoftheinstancetobepopulatedbyagiven

control.WeuseapairofattributesheresinceXFormspermits
thecreationofWebapplicationsthatusemultiplemodels,for
example,whencreatingacomplexapplicationthatneedsto
submitdatatomultiplelocationsontheWeb.Bindingattribute
modelidentifiesthemodelthatcontainstheinstancebeing
populated;AttributerefholdsanXPathlocatorthatidentifies
thelocationintheinstancethatisbeingpopulated.Binding
userinterfacecontrolstothemodelwasillustratedinFigure1.5
andFigure1.7.
Table3.2.CommonAspectsofXFormsUserInterfaceMarkup
Markup

Purpose
BindingAttributes(Section3.2.2)

model

Identifiesthemodelcontainingtheboundinstance

ref

Identifiessinglenodefromtheinstancethatisbound

nodeset

Identifiessetofnodesfromtheinstance

bind

Identifiesboundinstancedataviaabindingsite

CommonPresentationAttributes(Section3.2.3)

appearance

Presentationhintoneoffull,compact,orminimal

class

CSSselectortospecifyrenderingstyle
CommonPresentationChildElements(Section3.2.3)

label

Labelfortheuserinterfacecontrol

help

Helptextfortheuserinterfacecontrol


hint

Tooltipfortheuserinterfacecontrol

alert

Messagetodisplayincaseofinvalidinput

CommonInteractionAttributes(Section3.2.4)
accesskey


Specifieskeyboardshortcutfornavigatingtothiscontrol

navindex

Specifiespositionofthecontrolinthenavigationsequence

inputmode

Facilitatestextinputonsmalldevices

eventing

XMLEventsattributesforwiringupevents

incremental

Specifiesiftextinputgeneratescontinuousstreamofevents
CommonInteractionChildElements(Section3.2.4)

action

DeclarativeactionhandlersdefinedbyXForms

Thus,bindingattributeswireuserinterfacecontrolstothe
appropriateportionoftheunderlyingXFormsmodel.Inaddition
toattributepair(model,ref)describedearlier,XFormsprovides
asyntacticshortcutforcreatingbindingexpressionsthat
involvecomplexXPathexpressions.WhendefiningtheXForms
model,theauthorcanidentifycertainlocationswitha

designatediddeclaredviaelement bind .Suchbindingsites
canbelaterusedwhenbindinguserinterfacecontrolsby
specifyingtheidofthebindingsiteasthevalueofattribute
bind.
Thismechanismisusefulwhenbindingmultiplecontrolstothe
samelocationinmultipageforms.Forinstance,consideratax
formthatcollectsmultipleitemsofinformationanddisplaysthe
mostimportantitemsonasummarypageseeFigure3.2.


Figure3.2Usingbindingsitesforconnectinguser
interfacecontrolstothemodel.
<htmlxmlns=" /><head>
<modelxmlns=" /><instance>
<dataxmlns="">...<wages/>...</data>
</instance>
<!--identifybindingsite-->
<bindref="/data/wages"id="wages"/>
</model></head>
<body>

Page1


<groupxmlns=" />...<inputbind="wages">...</input>...
</group>...

SummaryPage


<groupxmlns=" /><outputbind="wages">
<label>TotalWagesReported</label>
</output></group>
</body></html>
Theauthorcanidentifythoseinformationitemsthatappearon
multiplepagesasbindingsiteswhendefiningthemodel.Later,

whenauthoringtheuserinterface,attributebindcanbeused
whenbindinguserinterfacecontrolstothesebindingsites.
Thishastheadvantageifthestructureoftheinstanceneedsto
bechangedatalaterdate.Whensuchchangesaremade,the
XPathlocatorsneedbeeditedonlyinoneplace,namelythe
modelwherethebindingsiteisdeclared.Iftheattributepair
(model,ref)wereusedinthisscenario,thiswouldrequirethe
editingofthebindingattributesonthedifferentuserinterface
controls.Thissaid,usingattributes(model,ref)ismore


convenient,exceptinsuchcomplexexamples,sincetheextra
levelofindirectionintroducedbytheuseofbindingsitesmakes
theresultingmarkuplessobvious.

3.2.3RenderingUserInterfaceControls
End-userexperienceiscontrolledviaasetofattributesand
childelementscommontoallXFormsuserinterfacecontrols.
Thesecommonmarkupconstructsholdmetadataassociated
withtheuserinterfacecontrol,forexample,thelabeltobe
displayedtotheuser;theyalsoencapsulatepresentationhints
thatcanbeusedindeliveringthedesiredpresentation.

CommonPresentationAttributes

appearance Attributeappearancecanbeusedbytheauthortospecifypresentational
hints.XFormsspecifiesthreepredefinedvaluesforthisattribute:
1. full
compact
minimal

Themeaningofthesepredefinedvaluesisafunctionoftheuserinterface
control.Asanexample,appearance="full"mightbeusedtorequestthata
select selectioncontrolbepresentedasalistofcheckboxeswithallthe
availablechoicesbeingvisibletotheuser.Incontrast,
appearance="minimal"mightbeusedtorequestthatthesamecontrolbe
renderedtotakeupaminimalamountofdisplayrealestateand,asaresult,
appearasapop-upmenuinavisualinterface.
Inadditiontothepredefinedvalues,attributeappearanceencourages
innovationbyacceptingapplication-specificvaluesaslongasthesevalues
areproperlynamespacequalified.Thus,anauthorcreatingan input
controlthatbindstoavalueoftypexsd:datecanrequestthatthecontrol
bepresentedusingacustomdatepickerwithmarkup(showninFigure3.3).
Theadvantageofthisdesignisthatuseragentsnotcapableofusingthe
customdatepickercontrolcanstilleffectivelyrepresenttheuserinterfaceby
usingaregulartextinputfield.


Figure3.3Requestingacustomdatepickervia
attributeappearance.
appearance="my:date-picker">
<label>InvitationDate</label>...</input>
class

WhenusingXFormscontrolsinHTML,attributeclasscanspecifyaCSSstyle
tobeused.

CommonPresentationChildElements

label Holdsthelabelforthecontaininguserinterfacecontrol

help Holdshelptexttobedisplayedonrequest
hint Holdstooltipinformationforthecontainingcontrol
alert Holdsamessagetobedisplayediftheformcontrolisaninvalidstate,forexample,
whenanillegalvalueisenteredbytheuser

Notethatelements label , help , hint ,and alert whenused
mustappearinthisspecificorder.
Element label isrequiredonallXFormsuserinterface
controls.Inadditiontoprovidingalabelfortheuserinterface
control,thecontentofthiselementcanbeusefulto
accessibilityaids;forexample,anaccessibilityaidmightspeak
thecontentsofthiselementwhentheusernavigatestoa
control.
Element label wasdesignedtobeachildelementoftheuser
interfacecontrolinordertoimproveaccessibilityofelectronic
forms.TraditionalHTMLformcontrolsdidnotcapturethelabel
aspartofthemarkupfortheuserinterfacecontrol;this


resultedinauthorsvisuallyaligninglabelsforuserinterface
controlsusingHTMLtables.Thoughthisdeliversavisual
presentationthatclearlydisplaystheassociationbetweenlabels
anduserinterfacecontrols,itpresentsaseriousaccessibility
problem.Accessibilityaidswereforcedtoguesstheassociation
betweenlabelsandcontrolsbyexaminingthevisuallayout.By
makingelement label arequiredchildofalluserinterface
controls,XFormstakesamajorstepforwardwithrespectto
enhancingtheaccessibilityofWebapplications.
Elements label , help , hint ,and alert candirectly
encapsulatetheinformationtobeshowntotheuser.

Alternatively,thismetadatacanbespecifiedindirectlyby
specifyingaURIasthevalueofattributesrc.Specifyingsuch
metadataindirectlycanbehelpfulwhencreatinguserinterfaces
thatneedtobelocalized.Insuchcases,onecancreatelocalespecificsetsofmessagesanduseattributesrctorefertothe
messages.

3.2.4InteractionBehaviorofFormControls
End-userexperiencethelookandfeeldeliveredbyauser
interfaceisafunctionoftheend-userpresentationaswellas
thebehaviorexhibitedbytheuserinterfaceinresponsetouser
actionssuchaskeypressesandmouseclicks.Interaction
behaviorofXFormsuserinterfacecontrolscanbecustomized
viathecommonattributesandchildelementsdescribedinthis
section.

CommonInteractionAttributes

accesskey

Specifiestheshortcutkeytonavigatetothecontainingcontrol.

navindex

Specifiesthepositioninthenavigationsequence.


inputmode Attributeinputmodewasaddedtouserinterfacecontrolsthatcollecttextual
inputtofacilitatetextentryondifferentdevices.Thisfeatureisespecially
usefulonsmalldevicesthatneedtoprovidethenecessaryaidstoenable
efficientuserinputwhenusingvariousinternationalcharactersets.

eventing

XMLEventsattributepair(event,handler)isusedtoturnuserinterface
controlsintolisteners.Attributeeventspecifiestheeventtolistenfor;
attributehandlerspecifiesthehandlertobeinvokeduponreceivingthe
specifiedevent.

incremental Optionalbooleanattributeincremental(falsebydefault)specifiesifthe
containinguserinterfacecontrolfireseventsasthevalueisbeingentered.
Thisisanadvancedfeaturethatmightbeusedbyuseragentstoupdate
differentpartsofaformastheuserisenteringavalue;leveragingthe
XFormsprocessingmodelforimplementingsophisticateduserinterfaceswill
bedescribedinalaterchapter.

Attributesaccesskeyandnavindexareimportantaccessibility
featuresfirstintroducedinHTML4.Specifyingkeyboard
shortcutsviaattributeaccesskeycanenhancetheusabilityof
anonlineformbyenablingtheusertonavigatedirectlytoa
controlviathekeyboard.Specifyingthepositionofauser
interfacecontrolinthenavigationsequenceviaattribute
navindexgivestheauthortheabilitytoinfluencetheorderin
whichtheusernavigatesthroughasequenceofcontrols.

CommonInteractionChildElement

action Holdsoneormoreactionhandlers.XFormsdefinesasetofdeclarativeevent
handlersthatprovidesfunctionalitycommonlyfoundinonlineforms.Allofthese
handlerscanappearwithinXFormsuserinterfacecontrols.Suchhandlersare
executedwhentheuserinterfacecontrolisactivatedbytheuser.



3.3CollectingTextInput
Inputtingfree-formtextualinputisperhapsoneofthemost
commontaskswhenworkingwithelectronicforms.Infact
electronicformscanbeviewedasameansofcollecting
semistructuredinformationfromtheuserandautomatically
taggingsuchinformationforlaterprocessing.Thus,atravel
reportmightbemodeledasanelectronicformwheremostif
notallofthefieldscollectfree-formtextualinputfromtheuser.
Yet,whenthetravelreportisfilledinusingawell-designed
formthatpopulatesanunderlyingdatamodelliketheone
providedbyXForms,theinformationthatiscollectedis
immediatelyreadyforfurthermachineprocessing.Incontrast,
ifthesametravelreportweredirectlyauthoredasaword
processordocument,thedatacollectedbythetravelreport
wouldneedtobereenteredintotherelevantsystemsinorder
tobeprocessedfurther.
Asanexample,consideramoredetailedversionofthe
questionnaireformintroducedinSection1.2.1andshownin
Figure3.4.Oncetheinformationcollectedbythequestionnaire
ismodeledusingXMLSchema,bindingasetofuserinterface
controlsthatfacilitateenteringthisinformationcreatesan
efficientuserinterfaceforeditingandmaintainingXML
documentsthatconformtothequestionnaireschema.

Figure3.4Datacollectedbythequestionnaire.
<questionnairexmlns:q=" /><name><first/><initial/><last/></name>
<emailxsi:type="q:email"/>
<home-phonexsi:type="q:phone"/>
<work-phonexsi:type="q:phone"/>

<address>


<name/><street/><city/><state/>
<zipxsi:type="q:zip"/>
</address>
<agexsi:type="xsd:integer"/>
<date-of-birthxsi:type="xsd:date"/>
</questionnaire>
XFormsprovidesthreevariantsofthegenericentersometext
userinterfacecontrol,allofwhichhavethesamemarkup
structure:

input

Editfieldforenteringvalues

secret

Forenteringavaluethatshouldnotbeechoedasitisentered

textarea Forenteringmultiplelinesoftext,forexample,thebodyofane-mailmessage

WedemonstratetheuseofthesecontrolstoauthorasimpleemailapplicationinFigure3.5.

Figure3.5Sendinge-mailusingXForms.
<htmlxmlns=" /><head><linkrel="stylesheet"href="email.css"/>
<modelxmlns=" />id="m1"schema="email.xsd">
<instance>
<emailxmlns="">

<fromtype="email"/><totype="email"/>
<message/>
</email></instance>
</model></head>
<body>
<groupxmlns=" />

model="m1"ref="/email/from">
<labelclass="address">From</label>
<help>Enteryouremailaddress</help></input>
model="m1"ref="/email/to">
<labelclass="address">To</label>
<help>Recipient'saddress</help></input>
<secretclass="pin"ref="/email/pin">
<label>Pin</label>
<help>Secretphrase</help></secret>
model="m1"ref="/email/message">
<label>Message</label>
<help>...</help><hint>...</hint>
</textarea>...</group>
</body></html>
Controls input , secret ,and textarea useallofthe
commonmarkupattributesandchildelementsdescribedin
Section3.2.

3.3.1CustomizingInputControls
Controls input , secret ,and textarea arecommonly

renderedaseditboxesinavisualinterface.Notice,however,
thattheXFormsdesignleavesconsiderableflexibilityforaclient
toimplementthesecontrolsinamannermostsuitableforthe
facilitiesavailableontheaccessingdevice.
Thissectiongivesexamplesofhowdifferentclientsand
interactionmodalitiesmightleveragetheinformation
encapsulatedintheXFormsmarkuptodeliveranappropriate
end-userexperience.WeillustratethesescenariosusingtheemailapplicationintroducedinFigure3.5;seeFigure3.6forthe
visualrenderingofthisinterface.


Figure3.6.VisualpresentationoftheXFormsemailcomposer.

End-userexperienceisafunctionofthelookandfeeldelivered
byauserinterface.Asthephraselookandfeelimplies,thisis
madeupoftwohalves:thepresentationthatisdeliveredtothe
userandtheinteractionbehaviorexhibitedbytheuser
interface,thatis,thewaytheinterfacereactstodifferentuser
interfaceevents.
InXForms,thelookisauthoredviaCSS;thefeelisspecified
usingXMLEvents.NoticethatinFigure3.5,weused

class="address"
ontheinputcontrolsusedtocollectthefromandtoe-mail
addresses.Anaccompanyingemail.csscandefineappropriate
presentationalpropertiesthathelpvisuallydistinguishinput
fieldsthatcollecte-mailaddresses;thesameCSSstylesheet
mightalsodefinepresentationrulesforotheroutputmodalities,
forexample,auraloutput,bydefiningauralpresentationalrules
forclass="address"seeFigure3.7.[2]

[2]NotethatCSSuses|asthenamespaceseparatorcharacterunlikeXMLwhichuses .

:

Figure3.7CSSstylethatdefineshowfieldsfor
collectinge-mailaddressesshouldberenderedin
variouspresentationmodes.


<styletype="text/css">
@namespacexfurl( />xf|label{
font-weight:bold;font-size:20px;width:100px;}
xf|input::value.address{
font-weight:bold;width:500px;}
xf|secret::value.pin{
font-weight:bold;width:100px;}
xf|label.address{
color:white;background-color:blue;}
xf|textarea::value{
width:800px;}
@mediaspeech{
xf|input.address{pitch:1;pitch-range:9;
}
xf|label.address{pitch:1;pitch-range:9;
}}
</style>
FurthermediaspecificsectionsintheCSSfilemightfine-tune
thepresentationfordifferentdevicetypes.[3]Factoringout
presentationalaspectsfromtheuserinterfacemarkupand
delegatingthisresponsibilitytoCSSenabletheXFormsauthor

todesignapplicationsthatcanbedeliveredtoavarietyof
differentdevicesandpresentationmodalities.
[3]TheCSSWGisworkingonamechanismcalledCSSMediaQuerytofacilitatesuchfinetuning.

Theinteractionbehaviorofuserinterfacecontrolsisprimarily
determinedbythetypeoftheboundinstancedata.Asan
example,inputcontrolsthatbindtoinstancenodesoftype
datemightberenderedasadatepickercontrol.Thiscanbe
furthercustomizedviaattributeappearance.[4]XForms1.0
definesthreestandardvaluesforthisattributeasdescribedin
Section3.2.Inaddition,itallowsforcustomcontrolsby
allowingadditionalvaluesforattributeappearanceaslongas
suchvaluesarenamespacequalified.


[4]Asaworkinggroup,westruggledlongandhardtocomeupwithasuitablenameforthis
attributeandeventuallysettledonappearance,eventhoughitdoesnotdofulljustice.

TheexampleshowninFigure3.5takesadvantageofthis
featurebysettingattributeappearancetomy:emailonthe
inputcontrolsusedtocollecte-mailaddresses.[5]
[5]Wehaveused

my:asthenamespaceprefixforthee-mailapplication.

NoticefurtherthatwhendefiningthemodelinFigure3.5,we
declaredthetypeofthe/email/fromand/email/tofieldsto
bemy:email.AnXFormsclientthatincludesane-mailpickera
widgetthatcanaccesstheuser'se-mailaddressbookcanuse
thatwidgetratherthanaplaineditfield.Noticethatthis

mechanismenablesclientstodeliveranend-userexperience
thatbestleveragesthefacilitiesavailableonaclient.Atthe
sametime,theXFormse-mailapplicationcanbeusedona
devicethatdoesnotprovideane-mailpickercontrol.
Wedeclaredfielddate-of-birthinFigure2.11tobeoftype
xsd:date.Thisinformationcouldbeusedtopickacustomdate
pickercontrolwhenrenderinganinputcontrolthatbindstothe
date-of-birthfield.Bysettinganappropriatevaluefor
attributeinputmode,enteringthedateore-mailaddresscanbe
madeeasierwhenusingdevicessuchascellphones.More
ambitioususecaseswouldincludeinvokinganappropriate
speechinterfacethatiscapableofcollectingavaliddate;
advanceduserinteractionincludingspeechandmultimodal
interfaceswillbediscussedinChapter10.


1.3XFormsComponents
TheprevioussectiontracedthedevelopmentofasimpleWeb
applicationusingpresent-daytechnologiespredicatedbythe
HTMLformsarchitecture.Thequestionnaireapplicationevolved
fromasimplestand-aloneCGIscripttoamorecomplexWeb
applicationconsistingofsoftwarecomponentsdedicatedto
managingtheapplicationstatewithinaservlet,markuppages
designedtocreatetheuserinteraction,andnavigation
componentsdesignedtoconnectthevariousviewswiththe
applicationstate.Indoingso,wesawthattheWebdeveloper
neededtoimplementsignificantapplication-specific
functionalityincustomsoftwaretodeliverthequestionnaireto
aWebbrowser.
XFormsleveragesthepowerofusingXMLinmodeling,

collecting,andserializinguserinput.XFormshasbeendesigned
toabstractmuchofthisfunctionalityintoasetofcomponents
thatenabletheWebdevelopertorelyonastandardsetof
servicesandoff-the-shelfXMLtoolswhendevelopingthefinal
Webapplication.ThisallowstheWebdevelopertofocusonkey
aspectsoftheapplicationandrelyontheunderlyingXForms
platformforthefollowingservices:
Produceuserinterfacesappropriatefortheconnecting
device.
Provideinteractiveuserfeedbackviaautomatedclient-side
validation.
Validateuserinputontheserverautomatically.
Marshaluserinputontheserverintoastructuresuitablefor
theback-endapplication.


Basedonwhathasbeenobservedinthedesignoftoday'sWeb
applicationsandtheneedtodeliversuchapplicationstoan
ever-increasingarrayofend-userdevices,theoverallXForms
architecturehasbeendividedintothefollowingcomponents.A
keyfeatureofthisMVCdecompositionisaclearseparationof
themodelfromitsfinalpresentation.
Model AllnonpresentationalaspectsofaWebapplicationareencapsulatedbythe
XFormsdatamodel.ThedatamodelincorporatesanXMLinstancethatholdsuser
input,theconstraintsusedtovalidatethisinput,andthenecessarymetadata
abouthowthisuserinputshouldbecommunicatedtotheWebserver.
UI

XFormsdefinesauserinterfacevocabularythatconsistsofabstractcontrolsand
aggregationconstructsusedtocreaterichuserinterfaces.Theuserinterface

vocabularyisdesignedtocapturetheunderlyingintentoftheuserinteraction,
ratherthanitsfinalpresentationonanygivendeviceorinanyspecificmodality.
ThismakesitpossibletodeliverXForms-basedWebapplicationstodifferent
devicesandmodalities.

Submit ThisallowstheWebapplicationauthortospecifywhere,how,andwhatpiecesof
datatosubmittotheWebserver.Italsopermitstheapplicationdeveloperto
specifywhatactionstotakeuponreceivingaresponsefromtheserver.

1.3.1XFormsOverview
Next,wereexaminethequestionnaireandrecastitasan
XFormsapplication.Thequestionnairewillbecreatedasan
XHTMLdocumentthatcontainstheXFormsmodelanduser
interfacecomponents.Thefollowingsubsectionsdetaileachof
thesecomponentsandshowhowtheyareusedwithinan
XHTMLdocument.TheXFormsmodel(containedin model )is
placedwithinXHTMLelement head .XFormsuserinterface
controlscreatetheuserinteractionandappearwithinthebody
ofthedocument,thatis,withinXHTMLelement body ,andare
renderedaspartofthedocumentcontent.Inthisoverview,we
willdescribeafewoftheXFormsuserinterfacecontrolstogive
thereaderafeelforXFormsmarkup;subsequentchapterswill


detailalltheconstructsdefinedinXForms1.0.

1.3.2XFormsModel
Asbefore,westartbyenumeratingthevariousitemsofuser
informationcollectedbytheWebapplication.Sincewearenow
usingXML,wenolongerneedrestrictourselvestoaflatdata

modelconsistingofasetofuntypedname-valuepairs.Instead,
weencapsulatetheinformationcollectedfromtheuserina
structuredXMLdocument.ThisiscalledtheXMLinstance.
Further,wepickthestructureofthisXMLinstancetosuitthe
surveyapplicationseeFigure1.2.

Figure1.2Element instance declarestheXML
templatethatholdsuserinputanddefaultvalues.
<modelxmlns="id="p1">
<instance>

<name><first/><last/></name>
<age/><email/>
<address><street/><city/><zip/></address>
<birthday><day/><month/><year/></birthday>
<ssn>000-000-000</ssn>
<gender>m</gender>
</person>
</instance>
</model>
Noticethatcompounddataitemssuchasaddressarenow
modeledtoreflectthestructureofthedata,unlikewhenusing
flatname-valuepairs.Thisalsoobviatestheneedtointroduce
intermediatefieldstoholdportionsoftheuserdataandthe
subsequentneedtomarshalsuchintermediatefieldsintothe


structurerequiredbytheapplication.
Next,thisXMLinstancecanbeannotatedwiththevarious
constraintsspecifiedbytheapplication,forexample,ageshould

beanumber.WhenusingXML,suchconstraintsaretypically
encapsulatedinanXMLSchema[11]documentthatdefinesthe
structureoftheXMLinstanceseeFigure1.3.
[11] />
Figure1.3Constraininginstancedataby
specifyinganXMLSchema.
<modelxmlns=" />xmlns:xsd=" />schema="person.xsd"id="p1">
<instance>
...</person>
</instance>
</model>
Alternatively,suchtypeconstraintscanbespecifiedaspartof
theinstanceusingattributexsi:type[12]asshowninFigure1.4.
BothtechniqueshavetheirplaceinWebdevelopment;the
formerisespeciallyrelevantwhencreatingWebapplications
thataccessexistingbusinesslogic,andthelatterisusefulwhen
creatingaone-offWebapplicationwithrelativelysimpletype
constraints.
[12]Attributexsi:typeisdefinedbyXMLSchema.

Figure1.4XMLrepresentationofthedata
collectedbyaquestionnaireapplication,along
withsomesimpletypeconstraints.


" />xmlns=" />xmlns:xsd=" /><instance>

<name><first/><last/></name>
<agexsi:type="xsd:number"/>

<birthday>
<dayxsi:type="xsd:number"/>
<monthxsi:type="xsd:number"/>
<yearxsi:type="xsd:number"/>
</birthday>
<address>
<street/><city/><zip/>
</address>
<email/><ssn>000-000-000</ssn>
<gender>m</gender></person>
</instance></model>
Inthequestionnaireapplication,theconstraintsshowninFigure
1.4encapsulatetypeconstraintsthedefaulttypeisstring.
Complexschemastypicallyencapsulatemoreconstraints,such
asspecifyingtherulesforvalidatinga9-digitSocialSecurity
Numberorspecifyingthesetofvalidvaluesforthevarious
fields.Notethatthisexamplehasbeenkeptintentionally
simplelaterchapterswillbuildreal-worldexampleswherewe
willusethefullrichnessofthebuilt-intypemechanisms
providedbyXMLSchema.
TheadvantageofspecifyingsuchconstraintsusingXMLSchema
isthatthedevelopercanthenrelyonoff-the-shelfXMLparsers
tovalidatethedatainstanceagainstthesuppliedconstraints.
WiththeincreasingadoptionofXMLSchemabydatabase
vendors,complexbusinessapplicationsarelikelyalreadyto
haveanXMLSchemadefinitionforthedatamodel,andthe
developercanleveragesuchexistingassetswhencreatinga


Webapplication.XMLprocessorxerces[13]isavailablefromthe

ApacheprojectimplementsXMLSchemaandcanbeusedto
validatedatacollectedontheserver.
[13] />
Finally,theconstraintsonthedatainstancearenow
encapsulatedindeclarativeXMLasopposedtoimperative
programcodethusmakingiteasiertomaintainandrevisethese
constraintsusingXML-awaretoolswithouthavingtoreprogram
theapplication.

1.3.3XFormsUserInterface
ThissectioncreatesasampleXFormsuserinterfaceforthe
questionnaireapplicationandbindsthisuserinterfacetothe
XFormsdatamodeldefinedintheprevioussection.XForms
userinterfacemarkupappearswithinXHTMLelement body
alongwithotherdocumentmarkup.Noticethatbecauseofthe
separationofthemodelfromtheuserinteraction,XFormsuser
interfacemarkupcanappearanywherewithinthecontentsof
XHTMLelement body ;incontrast,whenusingHTMLforms,
userinterfacecontrolscanappearonlywithinelement form .
Inthequestionnaireapplication,XFormsuserinterfacecontrol
input canbeusedtocollecteachitemofdata.Userinterface
control input isintentionallydesignedtobegeneric.Thetype
ofinformationavailableabouttheunderlyingdataitem,for
example,birthdayisadate,canbeusedtoadvantagein
generatingauserinterfacerepresentationthatisappropriateto
theconnectingdevice,forexample,renderingitasacalendar
onadesktopbrowser.Noticethatinadditiontomakingthe
resultinguserinterfacecustomizablefortheconnectingdevice,
thisdesignprovidesarichlevelofaccessibilityforsupporting
userswithdifferentneeds.



UIControlInput
Here,wereviewdifferentaspectsofUIcontrol input insome
detail;laterchapterswillreviewalloftheXFormsuserinterface
controls.SeeFigure1.5forthemarkupthatcreatestheinput
fieldforobtainingtheuser'sageandFigure1.6fortheresulting
userinterface.XFormscontrolsencapsulatethefollowingpieces
ofinformationneededtorendertheinteractionandconnectthe
resulttotheappropriateportionoftheXFormsdatamodel:
Bindingattributesthatwirecontroltomodel
Metadataforgivingfeedbacktotheuser
Wiringupofeventsandeventhandlers
Presentationhints
CSSstylerules
Keyboardshortcutsandnavigationhints

Figure1.5Userinterfacecontrolforobtainingthe
user'sage.
<inputxmlns=" />xmlns:ev=" />model="p1"ref="/person/age"class="edit"
ev:event="DOMActivate"ev:handler="#speak"
accesskey="a"><label>Age</label>
<help>Specifyyourageasanumbere.g.,21</help>
<hint>Howyoungareyou?</hint>
<alert>Theageyouspecified,


×