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

Prentice hall java studio creator field guide jul 2004 ISBN 0131491687

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 (7.51 MB, 662 trang )






TableofContents
Index

Java™StudioCreatorFieldGuide
ByGailAnderson,PaulAnderson

Publisher :AddisonWesley
PubDate :June28,2004
ISBN :0-13-149168-7
Pages :368


Sun'sJavaStudioCreator(formerlyProject
Rave)offersyouaremarkablyproductive
visualenvironmentforbuilding,integrating,
anddeliveringbusiness-criticalapplications.
DirectfromSun,Java(TM)StudioCreator
FieldGuideisyourdefinitiveguidetoJava
StudioCreator.LeadingJavaplatform
instructorsandconsultantsGailandPaul
AndersonhelpyouuseJavaStudioCreatorto
simplifyandaccelerateyourentire
developmentprocess.


Onestepatatime,theAndersonswalkyou


through
MasteringJavaStudioCreator'sinterface
andworkflow
SimplifyingWebdevelopmentwith
JavaServer(TM)Facescomponents,
validators,anddataconverters
ControllingWebapplicationpageflowwith
thePageNavigationeditor
BuildingCreatorprojectswith
JavaBeans(TM)components
AccessingWebservicesusingXML-based
openstandards:acasestudyusingGoogle
WebServiceAPIs
Usingdatabasesanddata-aware
components--includingdetailedcoverage
ofnewJDBC(TM)RowSets
Customizingapplications:localization,
internationalization,andcustomvalidation
DebuggingwithCreator'sbuilt-indebugger


WithJavaStudioCreatorandthisbook,you'll
spendlesstimeonapplication"plumbing"-leavingmoretimeforthehigh-valuetasks
youreallycareabout.Simplyput,you'llget
moredone,faster...andhavemorefundoing
it.








TableofContents
Index

Java™StudioCreatorFieldGuide
ByGailAnderson,PaulAnderson

Publisher :AddisonWesley
PubDate :June28,2004
ISBN :0-13-149168-7
Pages :368



Copyright

Foreword

Preface
HowThisBookIsOrganized

AbouttheExamples




StayCurrentwithCreator!
NotationalConventions


AbouttheFrontCover


Acknowledgments

Chapter1.JavaTechnologyOverview
Section1.1.Introduction




Section1.2.TheJavaProgrammingLanguage




Section1.4.NetBeansSoftware




Section1.6.TheJ2EEArchitecture




Section1.8.JavaServerPagesTechnology

Section1.3.JavaBeansComponents

Section1.5.TheXMLLanguage
Section1.7.JavaServletTechnology
Section1.9.JDBCAPIandJDBCRowSets




Section1.10.JavaServerFacesTechnology




Section1.11.AntBuildTool
Section1.12.WebServices

Section1.13.KeyPointSummary


Chapter2.CreatorBasics
Section2.1.ExamplesInstallation




Section2.2.CreatorViews
Section2.3.SampleApplication

Section2.4.KeyPointSummary



Chapter3.JSFStandardComponents
Section3.1.JSFOverview




Section3.2.Components




Section3.4.JSFValidators

Section3.3.ComponentCatalog
Section3.5.JSFDataConverters

Section3.6.KeyPointSummary


Chapter4.PageNavigation
Section4.1.NavigationModel




Section4.2.SimpleNavigation





Section4.4.DynamicNavigation

Section4.3.NoncommandComponents
Section4.5.KeyPointSummary


Chapter5.JavaBeansComponents
Section5.1.WhatIsaBean?

Section5.2.LoginBeanComponent




Section5.3.LoanBeanComponent
Section5.4.KeyPointSummary


Chapter6.AccessingWebServices
Section6.1.GoogleWebServices

Section6.2.Validation




Section6.3.HTMLwithOutputText
Section6.4.DisplayingMultiplePages

Section6.5.KeyPointSummary



Chapter7.AccessingDatabases
Section7.1.DatabaseFundamentals




Section7.2.DataSources




Section7.4.DatabaseJoins



Section7.6.DatabaseRowInserts

Section7.3.AccessingtheMusicDatabase
Section7.5.DatabaseUpdates





Section7.7.DatabaseDeletions
Section7.8.KeyPointSummary



Chapter8.CustomizingApplicationswithCreator
Section8.1.LocalizinganApplication

Section8.2.InternationalizinganApplication




Section8.3.ControllingtheLocalefromtheApplication
Section8.4.CreatingCustomValidation

Section8.5.KeyPointSummary


Chapter9.DebuggingwithCreator
Section9.1.PlanningforDebugging




Section9.2.RunningtheDebugger




Section9.4.SteppingThroughtheCode





Section9.6.SettingWatches




Section9.8.DetectingExceptions




Section9.10.FinishDebugging



Section9.3.SettingBreakpoints
Section9.5.TrackingVariables
Section9.7.UsingtheCallStack
Section9.9.UsingLogFiles
Section9.11.KeyPointSummary
Index


Copyright
©2004GailAndersonandPaulAnderson
PublishedbyPrenticeHallPTR
Prentice-Hall,Inc.
UpperSaddleRiver,NJ07458
Allrightsreserved.Thisproductandrelateddocumentationare
protectedbycopyrightanddistributedunderlicensesrestricting
itsuse,copying,distribution,anddecompilation.Nopartofthis

productorrelateddocumentationmaybereproducedinany
formbyanymeanswithoutpriorwrittenauthorizationofSun
andit'slicensors,ifany.
RESTRICTEDRIGHTSLEGEND:Use,duplication,ordisclosure
bytheUnitedStatesGovernmentissubjecttotherestrictions
assetforthinDFARS252.227-7013(c)(1)(ii)andFAR
55.227.19.Theproductsdescribedinthisbookmaybe
protectedbyoneormoreU.S.patents,foreignpatents,or
pendingpatents.
TRADEMARKSHotJava,Java,JavaDevelopmentKit,J2EE,JSP,
JavaServerPages,EnterpriseJavaBeans,EJB,JDBC,J2SE,
Solaris,SPARC,SunOS,andSunSoftaretrademarksofSun
Microsystems,Inc.Allotherproductsorservicesmentionedin
thisbookarethetrademarksorservicemarksoftheir
respectivecompaniesororganizations.
PrenticeHallPTRoffersexcellentdiscountsonthisbookwhen
orderedinquantityforbulkpurchasesorspecialsales.For
moreinformation,pleasecontactU.S.Corporateand
GovernmentSales,1-800-382-3419,
ForsalesoutsideoftheU.S.,


pleasecontactInternationalSales,1-317-581-3793,

AcquisitionsEditor:GregoryG.Doench
EditorialAssistant:RaquelKaplan
SunMicrosystemsPressPublisher:MyrnaRivera
Textprintedonrecycledpaper
12345678910CRS0807060504
Firstprinting,June2004

SunMicrosystemsPress
APrenticeHallTitle


Foreword
ThedeveloperswhosetouttobuildJavaStudioCreatorhada
verydifficulttask:tomakethecreationofsophisticated
enterpriseapplicationseasy.
ThesetoftechnologiesthatcompriseJava2EnterpriseEdition
(J2EE)ishuge.ThegoodsideisthatJ2EEisbattlehardened
andfieldproventobeanexcellentbaseforlargescalemission
criticalapplications.Therearemanyexcellentbooksthatcover
alloftheaspectsofJ2EEingreatdetail.Butallofthisleadsto
thebadsideofJ2EE:itcanbedifficultandtime-consumingto
learnanduse.TremendouseffortgoesintomakingJ2EEas
simpleaspossible,butitremainsdaunting.
JavaStudioCreatorisahugeleapinthesimplificationofthe
processofdevelopingJ2EEbasedwebapplications.Developers
don'tneedtodealwithallofthegorydetails:Creatorjust
handlesthem.Instead,developerscanfocusonwhattheir
applicationdoesandlookslikeinaverysimpleand
straightforwardway.Theyweavetogetherdatasourcesthrough
asimpledrag-and-dropinterface.VerylittleknowledgeofJava
orJ2EEisrequiredtodevelopapplicationsinCreator.Creator
notonlysimplifiestheprocess:italsoacceleratesit.
Thisbookcontainsallthatyouneedtoknowtogenerate
enterpriseapplicationsusingCreator.Itdoesn'trequirethatyou
knowanythingaboutJ2EEorevenJava:therearegentle
introductorychaptersthatleadyouthroughwhatyouneedto
know.Thisisagreatentrypointfordevelopersfromother

platforms(likeVisualBasic!)toentertheworldoflarge-scale,
mission-criticalapplications.It'sfun.Taketheplunge.
JamesGosling
SunMicrosystems,Inc.


Preface
You'reabouttoembarkonajourneythatwehopewillprove
bothenjoyableandfruitful.Certainlytheaimofanyapplication
developmenttoolistohelpdevelopersbecomeefficientand
allowthemtospendtimeoncreativetaskswhilethetool
silentlygeneratesthedrudgeryforthem.Tothatend,wehope
thisbookwillteachyoutheinsandoutsofCreatorsothatyou
canquicklybegintobuildwebapplications.Beforeyoustart,
we'dliketotakeamomenttoexplaintheorganizationofthe
bookandthe"methodbehindthemadness"ofourproject
examples.


HowThisBookIsOrganized
Chapter1introducestheworldofJavaanditssupporting
technologies.Creatordependsonthesewell-establishedJava
technologiestodoitsjob.WiththeJavaprogramminglanguage
andXML,JavaServerFacescomponentsystem,andNetBeans
toolbuildingtechnology,Creatorhastappedtheavailable
standards.Hereweprovideagentleintroductiontothese
topics,soyou'llgetthe"bigpicture"ofhowCreatorfitsintothe
Javaworld.WealsospendampletimeontheJava
programminglanguagesinceyouwilluseJavaoftenwith
Creator.Ifyoucomefromanotherprogrammingenvironment,

wewantyoutofeelcomfortablerightawaywiththemyriadof
piecesthatmakeupaJava-basedwebapplication.
Chapter2introducesCreator,withtheaimofgettingyouupto
speedwithitsvariouswindows,thedesigncanvas,andits
editors.Agoodtoolletsyouaccomplishtasksintheorderthat's
bestforthedeveloper.Knowinghowtomoveaboutwithina
Creatorprojectwillquicklymakeyouproductive.You'llalso
buildyourfirstprojectfromscratch.
Chapter3isyour"ComponentsCatalog."Thisreferencechapter
letsyouchoosethebestcomponentforyourapplicationfrom
Creator'sstoreofcomponents,validators,anddataconverters.
Alltheprojectsthatyoubuildusethesecomponents,soaswe
discusseachone,we'llpointyoutoplacesinthebookwhere
youcanseehowtheywork.
Chapter4introducesPageNavigationinCreator.You'lllearn
howtospecifypageflowinawebapplicationandunderstand
whichcomponentsaresuitableforpagenavigation.We'llalso
discussCreator'snavigationmodelandillustratepage
navigationwithseveralprojectsthatyoucanbuild.
Chapter5explainsJavaBeanscomponents(beans).JavaBeans


componentsprovideoneofthekeysupportingtechnologiesthat
Creatoruses.Developerswhounderstandtheadvantagesof
JavaBeanscomponentscanbuildrobustapplicationswith
reusablecomponentsforrelatedorevolvingapplications.
Chapter6showsyouhowtoaccessawebservicefroma
Creator-builtapplication.Creatorbundlesafullselectionofweb
services,whichareallreadilyusableonceyouaddthemtoyour
project.Inthischapter,you'llbuildanapplicationthatusesthe

GoogleSearchWebService.
Chapter7showsyouhowtouseadatabasewithCreator.You'll
buildprojectswithessentialdatabaseoperations,suchasread,
update,insert,anddelete.Webapplicationsthattieinto
databasesareanimportantandcommonneedfortoday's
developer.Creator'sdata-awarecomponentsmakelinkingtoa
databaseeasyandstraightforward.
Chapter8showsyouhowtocustomizeawebapplicationfrom
Creator.You'lllearnhowtolocalizeanapplicationandhowto
internationalizeit.Wealsoshowyouhowtowriteandinstall
customvalidationmethods.
Chapter9showsyoudefensiveprogrammingtechniquesfor
webdevelopmentandhowtouseCreator'sdebuggerinyour
projects.You'lllearnhowtosetbreakpoints,lookattheserver
logfile,andrespondtoexceptions.Althoughthischapterisat
theendofthebook,weexpectyoutorefertoitassoonasyou
startdoingseriouswebdevelopment


AbouttheExamples
JavaStudioCreatorFieldGuideisanexample-drivenbook.You
maycertainlydownloadandrunalltheprojectsinthechapters,
buttherealvalueofthisbookcomesfromdoingthese
examplesyourself,stepbystep.Youcanalwayscheckyour
workagainstourexamplesasyoubuildyourprojects,too.
ThedatabasechapterincludesasampleMusicdatabase,which
wealsoprovideinthedownloadbundle.Theexamplecodeis
availableatanFTPsiteforalltheprojectsinthisbook.Check
yourfirewalltoensurethatyoucanaccesstheFTPsite.Youcan
downloadtheexamplecodefromourwebsiteat




StayCurrentwithCreator!
Creatorisanevolvingproduct,somakesurethatyouvisitour
websiteattheaboveURL.We'llgiveyouupdatedexample
projects,includingnewcode(whichmaybedifferentthan
what'shereinthebook).We'llalsokeepyouuptodatewith
thenewestfeaturesofCreatorandanychangestotheproduct.
Don'tforgettocheckinwithus!


NotationalConventions
We'veappliedarather"lighthand"withfontconventionsinan
attempttokeepthepageuncluttered.Herearetheconventions
wefollow.
Element

FontandExample

attributename

valueattribute,cellpaddingattribute

codecomments

//Usereventcodehere...

componentname


textfieldloanAmount

Creatorcomponents

outputtext,textfield,dropdownlist

filename

color1.properties,Page1.jsp

Javaclass

String,Object,Integer

Javacode

username.setValue("rave4u")

JavaBeans
components

LoginBean,ColorBean,Page1

JSFELexpressions

#{Page1.colorBean.redValue}

JSPcode,HTMLcode

<f:loadBundle>,<img>


keycombinations

press<Alt-Shift-I>;press<Enter>

menuselections

ViewPage1JavaClass,Music>Tables

projectname

Login1,Echo


userinput

TypethetextMusic1,specifyloginBean


AbouttheFrontCover
I.M.Pei'sGlassPyramidisanaptsymbolforabookonJava
StudioCreator.Thepyramidservesastheentrancetothe
LouvreMuseuminParis.Trulyinternational,itwasdesignedby
aChinese-American,whoisbothanengineerandanartist.We
weredrawntoitselegantsimplicityofglassandlight,its
multiplefacets,andtheblendingofastructurethatismodern
yetsimultaneouslyrepresentativeofAncientEgypt.
JavaStudioCreatorisbuiltonthesameconceptoflayered
architecture.BasedonJavaServerFacestechnology,Creator
leveragestheexistingJava2PlatformEnterpriseEdition(J2EE)

architectureandofcourse,thesolidfoundationsofJavaandits
runtimeenvironment.Likewise,theGlassPyramidisan
extraordinaryexampleoflayeredarchitecturewhosebackdrop
isatraditionalRenaissancepalace.TheLouvreitselfhouses
artistictreasuresdatingfromantiquity,perhapsnonemore
famousthanLeonardodaVinci'sMonaLisa.
GailandPaulAnderson
AndersonSoftwareGroup,Inc.


Acknowledgments
Workingonthisprojecthasgivennewmeaningtotheterms
multitasking,bandwidth,anddistributedprocessing!Without
thehelpofothers,notonlywouldthistextbelackingin
timelinessandaccuracy,butitsveryexistenceisquestionable.
We'dliketothankoureditoratPrenticeHall,GregDoench,for
approachinguswiththisprojectideawhenneitherCreatornor
itsnameevenexisted.Hetrustedthatwecouldwriteat
breakneckspeedandpromisedsupportfrombothPrenticeHall
andSunMicrosystems.Hedeliveredonhispromises.
ValerieLipmanatSunMicrosystemsgaveuscrucialtechnical
supportthroughouttheentirewritingandtestingcycle.From
Creator'sfirsttechnologypreviewreleasetothelatestand
greatestbitshotfromtheamazingengineersthatbuiltthis
product,Valeriesupporteduswithquickturn-aroundemails
andphonecalls.WithoutValerie'sassistance,patience,and
investedeffort,wecouldnothavefinishedontime(noteven
close!).
ThankyoualsotoJimInscoreatSunMicrosystems.Hiswork
behindthescenesandhisrecognitionintheimportanceofa

companionbooktoCreatorhelpedsmooththetie-inswithSun.
Thankyoutoourcopyeditor,MaryLouNohr,whoisawizard
withwords.Herspeedandaccuracyatzippingthrougha300pagemanuscriptisimpressive.
We'dalsoliketothankBillHiggins,whoprovidedhelpful
suggestionsfromareader'sviewpointandPaulFleck,who
knowsabitabouttheworldofVB.JohnFulleratPearson
TechnologyGroupandBrettLintonfromCourierCompanies
helpedwithproduction.VickyHilpertofVietsbronn,Germany
helpedwiththeGermantranslationsandBlancaLazarohelped


withtheSpanish.Thanksalsotoourchildren(whoarenot
childrenanymore),SaraandKellen.
Lastly,we'dliketothankJamesGoslingforgivingusallJava.


Chapter1.JavaTechnologyOverview
TopicsinThisChapter
TheJavaProgrammingLanguage
JavaBeansComponents
NetBeansSoftware
TheXMLLanguage
TheJ2EEArchitecture
JavaServerFacesTechnology
JDBCAPI
AntBuildTool
WebServices
WelcometoCreator!CreatorisanIDE(IntegratedDevelopment
Environment)thathelpsyoubuildwebapplications.Whilemany
IDEsoutintheworlddothat,Creatorisuniqueinthatitisbuilt

onalayeredtechnologyanchoredinJava.Atthecoreofthis
technologyistheJavaprogramminglanguage.Javaincludesa
compilerthatproducesportablebytecodeandaJavaVirtual
Machine(JVM)thatrunsthisbytecodeonanyprocessor.Java
isanimportantpartofCreatorbecauseitmakesyourweb
applicationsportable.
ButJavaismorethanjustaprogramminglanguage.Itisalsoa


technologyplatform.Manylargesystemshavebeendeveloped
thatuseJavaastheircore.Thesesystemsarehighlyscalable
andprovideservicesandstructurethataddresssomeofthe
high-volume,distributedcomputingenvironmentsoftoday.


1.1Introduction
Creatordependsonmultipletechnologies,soit'sworthwhile
touchingontheminthischapter.Ifyou'renewtoJava,manyof
itspartsandacronymscanbedaunting.Javatechnologiesare
dividedintorelatedpackagescontainingclassesandinterfaces.
Tobuildanapplication,youmightneedpartsofonesystemand
partsofanother.Thischapterprovidesyouwitharoadmapof
Javatechnologiesanddocumentationsourcestohelpyou
designyourwebapplicationswithCreator.
We'llbeginwithanoverviewoftheJavaprogramming
language.ThiswillhelpyougetcomfortablewritingJavacode
tocustomizeyourCreatorapplications.Butbeforewedothat,
weshowyouhowtofindthedocumentationforJavaclasses
andmethods.Thiswillhelpyouusethemwithconfidencein
yourprograms.

MostofthedocumentationforaJavaApplicationProgram
Interface(API)canbefoundonline.Sometimesallyouneedis
thenameofthepackageorthesystemtofindoutwhatAPIa
class,interface,ormethodbelongsto.Javaconsistsofthebasic
language(allpackagesunderjava)andJavaextensions(all
packagesunderjavax).Onceyoulocateapackageonline,you
canexploretheinterfacesandclassesandlearnaboutthe
methodstheyimplement.
Here'sagoodstartingpointfortheJavaAPIdocumentation.
/>ThispagecontainslinkstotheJava2PlatformStandard
Edition,whichcontainsthecoreAPIs.Italsohasalinktoallof
theotherJavaAPIsandtechnologies,foundat


/>SincetheAPIschangewithimprovements,newfeatures,and
bugfixes,it'sbesttocheckthese"main"pagesforthemost
up-to-datedocumentation.
CreatorisalsobuiltonthetechnologyofJavaServerFaces
(JSF).YoucanfindthecurrentJSFAPIdocumentationat
/>JSFisdescribedaspartoftheJ2EETutorial,whichcanbefound
at
/>Theseareallimportantreferencesforyou.We'veincludedthem
atthebeginningofthisbooksoit'seasytofindthemlater
(whenyou'redeepinthechallengesofwebapplication
development).Fornow,let'sbeginwithJavaasaprogramming
language.Thenwe'lllookatsomeoftheothersupporting
technologiesonwhichCreatorisbuilt.


1.2TheJavaProgrammingLanguage

ThiscursoryoverviewoftheJavaprogramminglanguageisfor
readerswhocomefromanon-Javaprogrammingenvironment.
It'snotmeanttobeanin-depthreference,butastartingpoint.
MuchofCreatorinvolvesmanipulatingcomponentsthroughthe
designcanvasandthecomponents'propertysheets.However,
therearetimeswhenyoumustaddcodetoaJavapagebean
(thesupportingJavacodeforyourwebapplication'spage)or
useaJavaBeanscomponentinyourapplication.You'llwanta
basicunderstandingofJavatomoreeasilyuseCreator.

Object-OrientedProgramming
LanguageslikeCandBasicareprocedure-orientedlanguages,
whichmeansdataandfunctionsareseparated.Towrite
programs,youeitherpassdataasargumentstofunctionsor
makeyourdataglobaltofunctions.Thisarrangementcanbe
problematicwhenyouneedtohidedatalikepasswords,
customeridentificationcodes,andnetworkaddresses.
Procedure-orienteddesignsworkfinewhenyouwritesimple
programsbutareoftennotsuitabletomorecomplextaskslike
distributedprogrammingandwebapplications.Function
librarieshelp,buterrorhandlingcanbedifficultandglobal
variablesmayintroducesideeffectsduringprogram
maintenance.
Object-orientedprogramming,ontheotherhand,combines
dataandfunctionsintounitscalledobjects.LanguageslikeJava
hideprivatedata(fields)fromuserprogramsandexposeonly
functions(methods)asapublicinterface.Thisconceptof
encapsulationallowsyoutocontrolhowcallersaccessyour
objects.Itallowsyoutobreakupapplicationsintogroupsof
objectsthatbehaveinasimilarway,aconceptcalled



abstraction.InJava,youimplementanobjectwithaJavaclass
andyourobject'spublicinterfacebecomesitsoutsideview.
Javahasinheritancetocreatenewdatatypesasextensionsof
existingtypes.Javaalsohasinterfaces,whichallowobjectsto
implementrequiredbehaviorsofcertainclassesofobjects.All
ofthesethingshelpyouseparateanobject'simplementation
(insideview)fromitsinterface(outsideview).
Allobjectscreatedfromthesameclasshavethesamedata
type.Javaisastronglytypedlanguage,andallobjectsare
implicitlyderivedfromtypeObject(exceptthebuilt-inprimitive
typesofint,boolean,char,double,long,etc.).Youcan
convertanobjectfromonetypetoanotherwithaconverter.
Castingtoadifferenttypeisonlyallowediftheconversionis
knownbythecompiler.Creator'sJavaeditorhelpsyoucreate
well-formedstatementswithdynamicsyntaxanalysisandcode
completionchoices.You'llseehowthisworksinChapter2.
Errorhandlinghasalwaysbeenatoughproblemtosolve,but
withwebapplicationserrorhandlingisevenmoredifficult.
Processingerrorscanoccurontheserverbutneedtopropagate
inawell-behavedwaybacktotheuser.Javaimplements
exceptionhandlingtohandleerrorsasobjectsandrecover
gracefully.TheJavacompilerforcesprogrammerstousethe
built-inexceptionhandlingmechanism.
And,Javaforbidsglobalvariables,arestrictionthathelps
programmaintenance.

CreatingObjects
OperatornewcreatesobjectsinJava.Youdon'thavetoworry

aboutdestroyingthem,becauseJavausesagarbagecollection
mechanismtoautomaticallydestroyobjectswhichareno
longerusedbyyourprogram.


×