Tải bản đầy đủ - 0 (trang)
Chapter 23. Ajax-Enabled JavaServer Faces Web Applications

Chapter 23. Ajax-Enabled JavaServer Faces Web Applications

Tải bản đầy đủ - 0trang

withthatoftheviewer.

—EugéneDelacroix

Outline

23.1 Introduction

23.2 AccessingDatabasesinWebApplications





23.2.1 BuildingaWebApplicationThatDisplaysData

fromaDatabase







23.2.2 ModifyingthePageBeanFileforthe

AddressBookApplication



23.3 Ajax-EnabledJSFComponents

23.4 AutoCompleteTextFieldandVirtualForms





23.4.1 ConfiguringVirtualForms







23.4.2 JSPFilewithVirtualFormsandanAutoComplete

TextField







23.4.3 ProvidingSuggestionsforanAutoCompleteText

Field



23.5 GoogleMapsMapViewerComponent





23.5.1 ObtainingaGoogleMapsAPIKey







23.5.2 AddingaMapViewerComponenttoaPage







23.5.3 JSPFilewithaMapViewerComponent







23.5.4 PageBeanThatDisplaysaMapintheMap

ViewerComponent



23.6 WebResources



23.1.Introduction

Thischaptercontinuesourdiscussionofwebapplication



developmentwithseveraladvancedconcepts.Wediscuss

accessing,updatingandsearchingdatabasesinaweb

application,addingvirtualformstowebpagestoenable

subsetsofaform'sinputcomponentstobesubmittedtothe

server,andusingAjax-enabledcomponentlibrariestoimprove

applicationperformanceandcomponentresponsiveness.[Note:

ThischapterassumesthatyouknowJava.Tolearnmoreabout

Java,checkoutJavaHowtoProgram,SeventhEdition,orvisit

ourJavaResourceCentersat

www.deitel.com/ResourceCenters.html.]

Wepresentasingleaddressbookapplicationdevelopedinthree

stagestoillustratetheseconcepts.Theapplicationisbackedby

aJavaDBdatabaseforstoringthecontactnamesandtheir

addresses.

Theaddressbookapplicationpresentsaformthatallowsthe

usertoenteranewnameandaddresstostoreintheaddress

bookanddisplaysthecontentsoftheaddressbookintable

format.Italsoprovidesasearchformthatallowstheuserto

searchforacontactand,iffound,displaythecontact'saddress

onamap.Thefirstversionofthisapplicationdemonstrateshow

toaddcontactstothedatabaseandhowtodisplaythelistof

contactsinaJSFTablecomponent.Inthesecondversion,we

addanAjax-enabledAutoCompleteTextFieldcomponentand

enableittosuggestalistofcontactnamesastheusertypes.

Thelastversionallowsyoutosearchtheaddressbookfora

contactanddisplaythecorrespondingaddressonamapusing

theAjax-enabledMapViewercomponentthatispoweredby

GoogleMaps(maps.google.com).

AsinChapter22,thischapter'sexamplesweredevelopedin

Netbeans.Weinstalledasupplementarycomponentlibrary—the

JavaBluePrintsAjaxcomponentlibrary—whichprovides

theAjax-enabledcomponentsusedintheaddressbook

application.Instructionsforinstallingthislibraryareincludedin

Section23.3.TheseAjax-enabledcomponentsusetheDojo

Toolkit(whichweintroducedinChapter13)ontheclientside.



23.Ajax-EnabledJavaServer™Faces

WebApplications

Objectives

Inthischapteryouwilllearn:

Tousedataproviderstoaccessdatabasesfromweb

applicationsbuiltinNetbeans.

ToincludeAjax-enabledJSFcomponentsinaNetbeans

webapplicationproject.

Toconfigurevirtualformsthatenablesubsetsofaform's

inputcomponentstobesubmittedtotheserver.

Whateverisinanywaybeautifulhathitssourceof

beautyinitself,andiscompleteinitself;praiseforms

nopartofit.

—MarcusAureliusAntoninus

Thereissomethinginaface,Anair,andapeculiar

grace,Whichboldestpainterscannottrace.

—WilliamSomerville

Catosaidthebestwaytokeepgoodactsinmemory

wastorefreshthemwithnew.

—FrancisBacon

Ineverforgetaface,butinyourcaseI'llmakean

exception.

—GrouchoMarx

Paintingisonlyabridgelinkingthepainter'smind



withthatoftheviewer.

—EugéneDelacroix

Outline

23.1 Introduction

23.2 AccessingDatabasesinWebApplications





23.2.1 BuildingaWebApplicationThatDisplaysData

fromaDatabase







23.2.2 ModifyingthePageBeanFileforthe

AddressBookApplication



23.3 Ajax-EnabledJSFComponents

23.4 AutoCompleteTextFieldandVirtualForms





23.4.1 ConfiguringVirtualForms







23.4.2 JSPFilewithVirtualFormsandanAutoComplete

TextField







23.4.3 ProvidingSuggestionsforanAutoCompleteText

Field



23.5 GoogleMapsMapViewerComponent





23.5.1 ObtainingaGoogleMapsAPIKey







23.5.2 AddingaMapViewerComponenttoaPage







23.5.3 JSPFilewithaMapViewerComponent







23.5.4 PageBeanThatDisplaysaMapintheMap

ViewerComponent



23.6 WebResources



23.1.Introduction

Thischaptercontinuesourdiscussionofwebapplication



developmentwithseveraladvancedconcepts.Wediscuss

accessing,updatingandsearchingdatabasesinaweb

application,addingvirtualformstowebpagestoenable

subsetsofaform'sinputcomponentstobesubmittedtothe

server,andusingAjax-enabledcomponentlibrariestoimprove

applicationperformanceandcomponentresponsiveness.[Note:

ThischapterassumesthatyouknowJava.Tolearnmoreabout

Java,checkoutJavaHowtoProgram,SeventhEdition,orvisit

ourJavaResourceCentersat

www.deitel.com/ResourceCenters.html.]

Wepresentasingleaddressbookapplicationdevelopedinthree

stagestoillustratetheseconcepts.Theapplicationisbackedby

aJavaDBdatabaseforstoringthecontactnamesandtheir

addresses.

Theaddressbookapplicationpresentsaformthatallowsthe

usertoenteranewnameandaddresstostoreintheaddress

bookanddisplaysthecontentsoftheaddressbookintable

format.Italsoprovidesasearchformthatallowstheuserto

searchforacontactand,iffound,displaythecontact'saddress

onamap.Thefirstversionofthisapplicationdemonstrateshow

toaddcontactstothedatabaseandhowtodisplaythelistof

contactsinaJSFTablecomponent.Inthesecondversion,we

addanAjax-enabledAutoCompleteTextFieldcomponentand

enableittosuggestalistofcontactnamesastheusertypes.

Thelastversionallowsyoutosearchtheaddressbookfora

contactanddisplaythecorrespondingaddressonamapusing

theAjax-enabledMapViewercomponentthatispoweredby

GoogleMaps(maps.google.com).

AsinChapter22,thischapter'sexamplesweredevelopedin

Netbeans.Weinstalledasupplementarycomponentlibrary—the

JavaBluePrintsAjaxcomponentlibrary—whichprovides

theAjax-enabledcomponentsusedintheaddressbook

application.Instructionsforinstallingthislibraryareincludedin

Section23.3.TheseAjax-enabledcomponentsusetheDojo

Toolkit(whichweintroducedinChapter13)ontheclientside.



23.2.AccessingDatabasesinWeb

Applications

Manywebapplicationsaccessdatabasestostoreandretrieve

persistentdata.Inthissection,webuildawebapplicationthat

usesaJavaDBdatabasetostorecontactsintheaddressbook

anddisplaycontactsfromtheaddressbookonawebpage.

Thewebpageenablestheusertoenternewcontactsinaform.

ThisformconsistsofTextFieldcomponentsforthecontact'sfirst

name,lastname,streetaddress,city,stateandzipcode.The

formalsohasaSubmitbuttontosendthedatatotheserver

andaClearbuttontoresettheform'sfields.Theapplication

storestheaddressbookinformationinadatabasenamed

AddressBook,whichhasasingletablenamedAddresses.(We

providethisdatabaseintheexamplesdirectoryforthischapter.

Youcandownloadtheexamplesfrom

www.deitel.com/books/ajaxfp/).Thisexamplealsointroduces

theTableJSFcomponent,whichdisplaystheaddressesfromthe

databaseintabularformat.WeshowhowtoconfiguretheTable

componentshortly.



23.2.1.BuildingaWebApplicationThatDisplays

DatafromaDatabase

WenowexplainhowtobuildtheAddressBookapplication'sGUI

andsetupadatabindingthatallowstheTablecomponentto

displayinformationfromthedatabase.Wepresentthe

generatedJSPfilelaterinthesection,andwediscussthe

relatedpagebeanfileinSection23.2.2.Tobuildthe

AddressBookapplication,performthefollowingsteps:



Step1:CreatingtheProject

InNetbeans,createaVisualWebApplicationprojectnamed

AddressBook.RenametheJSPandpagebeanfilesto

AddressBookusingtherefactoringtools.



Step2:CreatingtheFormforUserInput

InDesignmode,addaStaticTextcomponenttothetopofthe

pagethatreads"Addacontacttotheaddressbook:"and

usethecomponent'sstylepropertytosetthefontsizeto

18px.AddsixTextFieldcomponentstothepageandrename

themfnameTextField,lnameTextField,streetTextField,

cityTextField,stateTextFieldandzipTextField.Seteach

TextField'srequiredpropertytotruebyselectingtheTextField,

thenclickingtherequiredproperty'scheckbox.LabeleachText

FieldwithaLabelcomponentandassociatetheLabelwithits

correspondingTextField.Finally,addaSubmitandaClearbutton.

SettheSubmitbutton'sprimarypropertytotruetomakeit

standoutmoreonthepagethantheClearbuttonandtoallow

theusertosubmitanewcontactbypressingEnterratherthan

byclickingtheSubmitbutton.SettheClearbutton'sreset

propertytotruetopreventvalidationwhentheuserclicksthe

Clearbutton.Sinceweareclearingthefields,wedon'tneedto

ensurethattheycontaininformation.Wediscusstheaction

handlerfortheSubmitbuttonafterwepresentthepagebean

file.TheClearbuttondoesnotneedanaction-handlermethod,

becausesettingtheresetpropertytotrueautomatically

configuresthebuttontoresetallofthepage'sinputfields.

Whenyouhavefinishedthesesteps,yourformshouldlooklike

Fig.23.1.

Figure23.1.AddressBookapplicationformforaddinga

contact.

[Viewfullsizeimage]



Step3:AddingaTableComponenttothePage

DragaTablecomponentfromtheBasicsectionofthePaletteto

thepageandplaceitjustbelowthetwoButtoncomponents.

NameitaddressesTable.TheTablecomponentformatsand

displaysdatafromdatabasetables.InthePropertieswindow,

changetheTable'stitlepropertytoContacts.Weshowhowto

configuretheTabletointeractwiththeAddressBookdatabase

shortly.



Step4:CreatingaJavaDBDatabase

ThisexampleusesadatabasecalledAddressBooktostorethe

addressinformation.Tocreatethisdatabase,performthe

followingsteps:

1. SelectTools>JavaDBDatabase>CreateJavaDBDatabase....

2. Enterthenameofthedatabasetocreate(AddressBook),a

username(iw3htp4)andapassword(iw3htp4),thenclick

OKtocreatethedatabase.

IntheNetbeansRuntimetab(totherightoftheProjectsandFiles

tabs),theprecedingstepscreateanewentryintheDatabases

nodeshowingtheURLofthedatabase

(jdbc:derby://localhost:1527/AddressBook).ThisURL

indicatesthatthedatabaseresidesonthelocalmachineand

acceptsconnectionsonport1527.



Step5:AddingaTableandDatatothe

AddressBookDatabase

YoucanusetheRuntimetabtocreatetablesandtoexecuteSQL

statementsthatpopulatethedatabasewithdata:

1. ClicktheRuntimetabandexpandtheDatabasesnode.



2. Netbeansmustbeconnectedtothedatabasetoexecute

SQLstatements.IfNetbeansisalreadyconnected,proceed

toStep3.IfNetbeansisnotconnectedtothedatabase,the

icon appearsnexttothedatabase'sURL

(jdbc:derby://localhost:1527/AddressBook).Inthis

case,rightclicktheiconandclickConnect....Onceconnected,

theiconchangesto .

3. ExpandthenodefortheAddressBookdatabase,rightclick

theTablesnodeandselectExecuteCommand...toopenaSQL

CommandeditorinNetbeans.Weprovidedthefile

AddressBook.sqlinthischapter'sexamplesfolder.Open

thatfileinatexteditor,copytheSQLstatementsandpaste

themintotheSQLCommandeditorinNetbeans.Then,

highlightalltheSQLcommands,rightclickinsidetheSQL

CommandeditorandselectRunSelection.Thiswillcreatethe

AddressestablewiththesampledatashowninFig.23.2.

YoumayneedtorefreshtheTablesnodeoftheRuntimetab

toseethenewtable.

Figure23.2.Addressestabledata.

FirstName LastName Street



City



State Zip



Bob



Green



5BaySt.



San

Francisco



CA



94133



Liz



White



1005thAve. NewYork



NY



10011



Mike



Brown



3600Delmar

Blvd.



MO



63108



Mary



Green



300

Boston

Massachusetts

Ave.



MA



02115



John



Gray



500SouthSt. Philadelphia PA



19147



Meg



Gold



1200Stout

St.



80204



St.Louis



Denver



CO



James



Blue



1000Harbor

Ave.



Seattle



WA



98116



Sue



Black



1000Michigan Chicago

Ave.



IL



60605



Step6:BindingtheTableComponenttothe

AddressesTableoftheAddressBookDatabase

Nowthatwe'veconfiguredadatasourcefortheAddresses

databasetable,wecanconfiguretheTablecomponenttodisplay

theAddressBookdata.Simplydragthedatabasetablefromthe

ServerstabanddropitontheTablecomponenttocreatethe

binding.

Toselectspecificcolumnstodisplay,rightclicktheTable

componentandselectBindtoDatatodisplaytheBindtoData

dialogcontainingthelistofthecolumnsintheAddresses

databasetable(Fig.23.3).TheitemsundertheSelectedheading

willbedisplayedintheTable.Toremoveacolumn,selectitand

clickthe
example,soyoushouldsimplyclickOKtoexitthedialog.

Figure23.3.DialogforbindingtotheAddressestable.



Bydefault,theTableusesthedatabasetable'scolumnnamesin

alluppercaselettersasheadings.Tochangetheseheadings,

selectacolumnandedititsheaderTextpropertyinthe

Propertieswindow.Toselectacolumn,clickthecolumn'sname

intheDesignmode.Wealsochangedtheidpropertyofeach

columntomakethevariablenamesinthecodemorereadable.

InDesignmode,yourTable'scolumnheadsshouldappearasin

Fig.23.4.

Figure23.4.Tablecomponentafterbindingittoa

databasetableandeditingitscolumnnamesfordisplay

purposes.

[Viewfullsizeimage]



Anaddressbookmightcontainmanycontacts,sowe'dliketo

displayonlyafewatatime.Clickingthecheckboxnexttothe



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 23. Ajax-Enabled JavaServer Faces Web Applications

Tải bản đầy đủ ngay(0 tr)

×