Manyofthedesignationsusedbymanufacturersandsellerstodistinguishtheirproductsareclaimedastrademarks. Wherethosedesignationsappearinthisbook,andthepublisherwasawareofatrademarkclaim,thedesignationshave beenprintedwithinitialcapitallettersorinallcapitals. Theauthorsandpublisherhavetakencareinthepreparationofthisbook,butmakenoexpressedorimpliedwarranty ofanykindandassumenoresponsibilityforerrorsoromissions.Noliabilityisassumedforincidentalorconsequential damagesinconnectionwithorarisingoutoftheuseoftheinformationorprogramscontainedherein. Thepublisheroffersexcellentdiscountsonthisbookwhenorderedinquantityforbulkpurchasesorspecialsales, whichmayincludeelectronicversionsand/orcustomcoversandcontentparticulartoyourbusiness,traininggoals, marketingfocus,andbrandinginterests.Formoreinformation,pleasecontact: U.S.CorporateandGovernmentSales (800)382-3419 [email protected] ForsalesoutsidetheU.S.,pleasecontact: InternationalSales [email protected] VisitusontheWeb:www.phptr.com ThisBookIsSafariEnabled TheSafari®Enabledicononthecoverofyourfavoritetechnologybookmeansthebookisavailable throughSafariBookshelf.Whenyoubuythisbook,yougetfreeaccesstotheonlineeditionfor45days. SafariBookshelfisanelectronicreferencelibrarythatletsyoueasilysearchthousandsoftechnicalbooks,findcode samples,downloadchapters,andaccesstechnicalinformationwheneverandwhereveryouneedit. Togain45-daySafariEnabledaccesstothisbook: • Gotohttp://www.prenhallprofessional.com/safarienabled • Completethebriefregistrationform • EnterthecouponcodeM8IP-VNEG-CZHV-DIG8-1652 IfyouhavedifficultyregisteringonSafariBookshelforaccessingtheonlineedition,pleasee-mail [email protected]. LibraryofCongressCataloging-in-PublicationData On file ©2008PearsonEducation,Inc. Allrightsreserved.PrintedintheUnitedStatesofAmerica.Thispublicationisprotectedbycopyright,andpermission mustbeobtainedfromthepublisherpriortoanyprohibitedreproduction,storageinaretrievalsystem,ortransmis- sioninanyformorbyanymeans,electronic,mechanical,photocopying,recording,orlikewise.Forinformationre- gardingpermissions,writeto: PearsonEducation,Inc RightsandContractsDepartment 501BoylstonStreet,Suite900 Boston,MA02116 Fax(617)671-3447 ISBN0-13-158738-2 TextprintedintheUnitedStatesonrecycledpaperatR.R.DonnelleyinCrawfordsville,Indiana. Firstprinting,January2008 Preface … the challenges are for the designers of these applications: to forget what we think we know aboutthelimitationsoftheWeb,andbegintoimagineawider,richerrangeofpossibilities.It’s goingtobefun. —JesseJamesGarrett,AdaptivePath “Ajax:ANewApproachtoWebApplications” (adaptivepath.com/ideas/essays/archives/000385.php) Introduction WelcometoInternetandwebprogrammingandWeb2.0!Andwelcometoawalkthrough oftheWeb2.0phenomenonfromthetechnical,businessandsocialperspectives.We’ve worked hard to create what we hope you’ll find to be an informative, entertaining and challenginglearningexperience.AtDeitel&Associates,wewriteprogramminglanguage professionalbooksandtextbooksforPrenticeHall,delivercorporatetrainingworldwide anddevelopWeb2.0Internetbusinesses.Thisbookreflectstoday’sWeb2.0,Ajax-based, RichInternetApplication-developmentmethodologies. Thetechnologiesyou’lllearnhereareappropriateforexperiencedprofessionalswho build substantial information systems. You’ll find “industrial-strength” code examples. Wehaveattemptedtowriteinaclearandstraightforwardmannerusingbestpractices. Perhapsmostimportant,thebookpresentshundredsofworkingcodeexamplesand showstheoutputsproducedwhentheseexamplesarerenderedinbrowsersorrunoncom- puters.Wepresentallconceptsinthecontextofcompleteworkingprograms.Wecallthis the“live-codeapproach.”Allofthesourcecodeisavailablefordownloadfrom www.deitel.com/books/ajaxfp/ under the heading “Download Code Examples and Other Premium Content for Regis- teredUsers,”onceyou’veregisteredandloggedontooursite. The early chapters present a carefully paced introduction to “client-side” web pro- gramming, using the popular JavaScript language and the closely related technologies of XHTML (Extensible HyperText Markup Language), CSS (Cascading Style Sheets) and theDOM(DocumentObjectModel).ThematerialintheJavaScriptchapterspresentsa solid foundation for the deeper treatment of scripting in the Adobe Flash, Adobe Flex, PHP and Ruby on Rails chapters later in the book. Experienced programmers will read the early chapters quickly and find the treatment of scripting in the later chapters to be rigorousandchallenging. Today’susersareaccustomedtodesktopapplicationswithrichgraphicaluserinter- faces(GUIs),suchasthoseusedonApple’sMacOSXsystems,MicrosoftWindowssys- tems, various Linux systems and more. Users want applications that employ the xx Preface multimediacapabilitiesofgraphics,images,animation,audioandvideo.Theywantappli- cations that can run on the Internet and the web and communicate with other applica- tions. Users want to apply database technologies for storing and manipulating their businessandpersonaldata.Theywantapplicationsthatarenotlimitedtothedesktopor even to some local computer network, but that can integrate Internet and web compo- nents,andremotedatabases.Programmerswanttouseallthesecapabilitiesinatrulypor- tablemannersothatapplicationswillrunwithoutmodificationonavarietyofplatforms. Inthisbook,wepresentanumberofpowerfulsoftwaretechnologiesthatwillenable youtobuildthesekindsofsystems.Earlyinthebookwefocusonbuildingtheportions of web-based applications that reside on the client side (i.e.,the portions of applications that typically run in web browsers such as Mozilla’s Firefox or Microsoft’s Internet Explorer), using technologies such as the XHTML, JavaScript, CSS, Flash, Flex and ExtensibleMarkupLanguage(XML).Laterinthebookweconcentrateonusingtechnol- ogiessuchaswebservers,databases,PHP,RubyonRails,ASP.NET,ASP.NETAjaxand JavaServerFaces(JSF)tobuildtheserversideofweb-basedapplications.Theseportions ofapplicationstypicallyrunon“heavy-duty”computersystemsonwhichorganizations’ business-criticalwebsitesreside.Bymasteringthetechnologiesinthisbook,you’llbeable tobuildsubstantialweb-based,client/server,database-intensive,“multitier”applications. Ifyouhavequestionsasyoureadthisbook,[email protected]— we’llrespondpromptly.Forupdatesonthebookandthestatusofallsupportingsoftware, andforthelatestnewsonDeitelpublicationsandservices,visitwww.deitel.com.Signup atwww.deitel.com/newsletter/subscribe.htmlforthefreeDeitel®BuzzOnlinee-mail newsletterandcheckoutwww.deitel.com/ResourceCenters.htmlforourgrowinglistof Internetandwebprogramming,Internetbusiness,Web2.0andrelatedResourceCenters. EachweekweannounceourlatestResourceCentersinthenewsletter. Key Features Here’s some of the keyfeatures of Ajax, RichInternet Applications and Web Development forProgrammers: • Reflects today’s Web 2.0, Ajax-based, Rich Internet Application-development methodologies. • Coverage of the two leading web browsers—Internet Explorer and Firefox. All client-sideapplicationsinthebookruncorrectlyonbothbrowsers. • FocusonWeb2.0technologiesandconcepts. • ChapteronWeb2.0andInternetBusiness(reviewedbyleadersintheWeb2.0 community). • Focus on building Rich Internet Applications with the interactivity of desktop applications. • ChapteronbuildingAjax-enabledwebapplicationswith“raw”Ajaxandwiththe Dojo JavaScript libraries. Applications in this chapter demonstrate partial-page updatesandtype-aheadcapabilities. • Chapter on Adobe Flex—a Rich Internet Application framework for creating scalable,cross-platform,multimedia-richapplicationsfordeliverywithintheen- terpriseoracrosstheInternet. Architecture xxi • Chapteronrapidapplicationsdevelopmentofdatabase-drivenwebapplications withRubyonRails;alsodiscussesdevelopingAjaxapplicationswiththeProto- typeandScript.aculo.uslibraries. • TwochaptersonAdobeFlashCS3,includingbuildingacomputergame. • Significanttreatmentofclient-sidescriptingwithJavaScript. • SignificanttreatmentsofXHTMLDOMmanipulationandJavaScriptevents. • SignificanttreatmentofXMLDOMmanipulationwithJavaScript. • Chapter on building SOAP-based web services with Java and REST-based web serviceswithASP.NET(usingVisualBasic). • ChapteronPHP5. • CoverageofASP.NET,featuringASP.NETAjax. • JavaServerFaces(JSF)coverageemphasizingbuildingAjax-enabledJSFapplica- tions. • Client-sidecasestudiesthatenableyoutointeractwithpreimplementedserver- sideapplicationsandwebservicesthatwehostattest.deitel.com. • Case studies including Deitel Cover Viewer (JavaScript/DOM), Address Book (Ajax), Cannon Game (Flash), Weather/Yahoo! Maps Mashup (Flex), Mailing List(PHP/MySQL),MessageForumandFlickrPhotoViewer(RubyonRails), GuestBookandSecureBooksDatabase(ASP.NET),AddressBookwithGoogle Maps(JavaServerFaces)andBlackjack(JAX-WSwebservices). Allofthishasbeencarefullyreviewedbyateamof38distinguishedindustrydevelopers andacademics. AJAX, Rich Internet Applications and Web Development for Programmers Architecture This book focuses on Web 2.0 and Rich Internet Application (RIA) development. Our goalistodevelopwebtopapplicationsthathavetheresponsiveness,lookandfeeloftradi- tionaldesktopapplications.Deitel&Associates,Inc.hasevolvedintoadevelopmentor- ganization, while continuing its focus on programming languages textbook and professionalbookauthoring,andcorporatetraining.We’rebuildingtheinfrastructurefor the Internet businesses we’re designing and developing as part of our Web 2.0 Internet BusinessInitiative.Thisbookincludesdiscussionsofmanypracticalissueswe’veencoun- teredindevelopingthatinfrastructure. Figure1 shows the architecture of AJAX, Rich Internet Applications and Web Develop- mentforProgrammers.The book is divided into several parts. Chapter1 introduces Web 2.0 from the technical, business and social perspectives, and provides a foundation for understandingRichInternetApplicationdevelopment.Ifyouareaseriouswebdeveloper, you’llwanttotestyourwebapplicationsacrossmanybrowsersandplatforms.Theexam- ples for the book execute correctly on both Microsoft’s Internet Explorer 7 (IE7) and Mozilla’sFirefox2(FF2)browsers.Mostoftheexampleswillalsoworkinotherbrowsers suchasOperaandSafari,butmaynotworkonearlierbrowsers.MicrosoftWindowsusers should upgrade to IE7 and install Firefox; readers with other operating systems should installFirefox. xxii Preface Intro 1.Dive-Into®Web2.0 2.IntroductiontoXHTML 3.CascadingStyleSheets™(CSS) 4.JavaScript:IntroductiontoScripting 5.JavaScript:ControlStatementsI 6.JavaScript:ControlStatementsII ons ax 7JavaScript:Functions cati Aj 8.JavaScript:Arrays pli 9.JavaScript:Objects p A 10.DOM:ObjectModelandCollections net 11.JavaScript:EventModel nter 12.XMLandRSS hI 13.Ajax-EnabledRichInternetApplications c Ri ng 14.Adobe®Flash®CS3 nd mi 15.Adobe®Flash®CS3:BuildinganInteractiveGame a m 0 a 16.Adobe®Flex™2andRichInternetApplications Web2. Progr 1178..WDaetbabSaesrev:eSrsQ(LII,SMaynSdQALp,aAcDheO).NET2.0,JavaDB e Sid 19.PHP er- 20.RubyonRails v er 21.ASP.NET2.0andASP.NETAjax S d 22.JavaServer™Faces(JSF)WebApplications n a 23.Ajax-EnabledJSFWebApplications RIAs 24.WebServices o Fig.1 | ArchitectureofAJAX,RichInternetApplicationsandWebDevelopmentfor Programmers. The second part of the book, Chapters2–13, presents a detailed treatment of Ajax component technologies, including a comprehensive treatment of JavaScript that spans ninechaptersandconcludeswithChapter13’streatmentofAjaxdevelopment.Ajaxisnot a new technology—we’ve been writing about all but one of its component technologies since1999,andmanyofthetechnologiesexistedbeforethat.However,Ajaxisoneofthe key technologies of Web 2.0 and RIAs. Chapters2–13 cover “raw” Ajax programming, where you’ll handle the details yourself—several later chapters in the book demonstrate technologiesthatencapsulateAjaxfunctionalitytohelpyoueasilybuildAjax-basedappli- cationsthatoperateacrossawidevarietyofbrowsersandbrowserversionswithoutyour havingtobeconcernedwiththelow-leveldetails. The third part of the book, Chapters13–24, focuses on both the client and server sides of the GUI and the graphical part of RIA development. Here we cover client-side technologiessuchasAdobeFlashandAdobeFlexthatuse,orcanbecombinedwith,Ajax orAjax-likecapabilitiestodevelopRIAs.Eachofthesetechnologiesalsocanconsumeweb services.Next,wepresenttheserversideofwebapplicationdevelopmentwithdiscussions of web servers (IIS and Apache), databases, server-side scripting languages such as PHP and Ruby on Rails, and several server-side frameworks such as ASP.NET 2.0 and Java- Server Faces. We complete our server-side discussion with a chapter on building both SOAP-basedandREST-basedwebservices. You may have noticed that Chapter13, Ajax-Enabled Rich Internet Applications, overlapsthesecondandthirdpartsofthebook.Chapter13servesasabridgefrom“raw” Ajaxdevelopmentto“encapsulated”AjaxdevelopmentwiththeDojolibraries. DependencyChart xxiii Dependency Chart Figure2 illustrates the dependencies that exist among chapters in the book. An arrow pointingintoachapterindicatesthatitdependsonthecontentofthechapterfromwhich thearrowpoints.Forexample,Chapter24,WebServices,dependsonbothChapters21 and23.Werecommendthatyoureadallofagivenchapter’sdependenciesbeforereading thatchapter,thoughotherordersarepossible.We’vealsocommentedonsomeadditional dependenciesinthediagram’sfootnotes. Teaching Approach AJAX,RichInternetApplicationsandWebDevelopmentforProgrammerscontainsarichcol- lectionofexamples.Thebookconcentratesontheprinciplesofgoodsoftwareengineering andstressesprogramclarity.Weareeducatorswhoteachleading-edgetopicsinindustry classroomsworldwide.Dr.HarveyM.Deitelhas20yearsofcollegeteachingexperience and18yearsofindustryteachingexperience.PaulDeitelhas16yearsofindustryteaching experience.TheDeitelshavetaughtcoursesatalllevelstogovernment,industry,military andacademicclientsofDeitel&Associates. Live-CodeApproach.AJAX,RichInternetApplicationsandWebDevelopmentforProgram- mersisloadedwith“live-code”examples—eachnewconceptispresentedinthecontextof acompleteworkingwebapplicationthatisimmediatelyfollowedbyoneormorescreen capturesshowingtheapplication’sfunctionality.Thisstyleexemplifiesthewayweteach andwriteaboutprogramming;wecallthisthe“live-codeapproach.” SyntaxShading.Wesyntaxshadeallthecode,similartothewaymostintegrated-devel- opmentenvironmentsandcodeeditorssyntaxcolorcode.Thisimprovescodereadabili- ty—an important goal, given that this book contains about 18,000 lines of code in complete,workingprograms.Oursyntax-shadingconventionsareasfollows: comments appear in italic keywords appear in bold italic PHP, Ruby, ASP.NET, JSP delimiters and errors appear in bold black constants and literal values appear in bold gray all other code appears in black CodeHighlighting.Weplacewhiterectanglesaroundeachprogram’skeycodesegments. UsingFontsforEmphasis.Weplacethekeytermsandtheindex’spagereferenceforeach definingoccurrenceinbolditalictextforeasierreference.Weemphasizeon-screencom- ponentsintheboldHelveticafont(e.g.,theFilemenu)andemphasizeprogramtextinthe Lucidafont(e.g.,intx=5). WebAccess.Allofthesource-codeexamplesforAJAX,RichInternetApplicationsandWeb DevelopmentforProgrammersareavailablefordownloadfrom: www.deitel.com/books/ajaxfp/ Siteregistrationisquick,easyandfree.Downloadalltheexamples,thenruneachprogram asyoureadthecorrespondingtextdiscussions.Makingchangestotheexamplesandseeing theeffectsofthosechangesisagreatwaytoenhanceyourInternetandwebprogramming learningexperience. xxiv Preface RichInternetApplications Part1:Introduction 1DiveInto®Web2.0 Part2:Client-Side 2IntroductiontoXHTML RichInternet ApplicationsandAjax 3CascadingStyleSheets(CSS) 4JavaScript:IntroductiontoScripting nt 5JavaScript:ControlStatementsI e Cli 6JavaScript:ControlStatementsII x a Aj 7JavaScript:Functions Part3:RichInternet e ApplicationClient h T 8JavaScript:Arrays Technologies : 2 rt 9JavaScript:Objects 14AdobeFlashCS3 a P 15FlashCS3InteractiveGame 10DocumentObjectModel(DOM) 16AdobeFlex 11JavaScript:Events 12XMLandRSS 17WebServers 13Ajax-EnabledRIAs 18Database 19PHP 20RubyonRails 21ASP.NETandASP.NETAjax 22JavaServerFaces(JSF)1 Part4:RichInternet 23Ajax-EnabledJSFApplications1 ApplicationServer Technologies 24WebServices2 1.Chapters22–23requireknowledgeofJavaStandardEdition6. 2.Sections24.2–24.8requireChapters22–22.Section24.9requiresChapter21. Fig.2 | AJAX,RichInternetApplicationsandWebDevelopmentforProgrammerschapter dependencychart. TeachingApproach xxv Objectives. Each chapterbeginswithastatementof objectives. Thisletsyouknowwhat toexpectandgivesyouanopportunitytodetermineifyouhavemettheobjectivesafter readingthechapter. Quotations. The learning objectives are followed by quotations. Some are humorous; somearephilosophical;othersofferinterestinginsights.Wehopethatyouenjoyrelating thequotationstothechaptermaterial. Outline. Thechapteroutlinehelpsyouapproachthematerialinatop-downfashion,so youcananticipatewhatistocomeandsetacomfortablelearningpace. Illustrations/Figures.Abundantcharts,tables,linedrawings,programsandprogramout- putareincluded. ProgrammingTips.Weincludeprogrammingtipstohelpyoufocusonimportantaspects ofprogramdevelopment.Thesetipsandpracticesrepresentthebestwehavegleanedfrom acombinedsixdecadesofprogrammingandteachingexperience.Oneofourreaderstold usthatshefeelsthisapproachislikethehighlightingofaxioms,theoremsandcorollaries inmathematicsbooks—itprovidesabasisonwhichtobuildgoodsoftware. GoodProgrammingPractices GoodProgrammingPracticescallattentiontotechniquesthatwillhelpyouproduceprograms thatareclearer,moreunderstandableandmoremaintainable. 3.0 CommonProgrammingErrors Programmerstendtomakecertainkindsoferrorsfrequently.PointingouttheseCommonPro- grammingErrorsreducesthelikelihoodthatyou’llmakethesamemistakes. 3.0 Error-PreventionTip Thesetipscontainsuggestionsforexposingbugsandremovingthemfromyourprograms;many describeaspectsofprogrammingthatpreventbugsfromgettingintoprogramsinthefirstplace. 3.0 PerformanceTip These tips highlight opportunities for making your programs run faster or minimizing the amountofmemorythattheyoccupy. 3.0 PortabilityTip WeincludePortabilityTipstohelpyouwritecodethatwillrunonavarietyofplatformsand toexplainhowtoachieveahighdegreeofportability. 3.0 SoftwareEngineeringObservation TheSoftwareEngineeringObservationshighlightarchitecturalanddesignissuesthataffect theconstructionofsoftwaresystems,especiallylarge-scalesystems. 3.0 ThousandsofIndexEntries.Wehaveincludedanextensiveindexwhichisespeciallyuseful whenyouusethebookasareference. “Double Indexing” of Live-Code Examples. For every source-code program in the book, weindexthefigurecaptionbothalphabeticallyandasasubindexitemunder“Examples.” Thismakesiteasiertofindexamplesusingparticularfeatures. xxvi Preface AJAX, Rich Internet Applications and Web Development for Programmers Software Downloads and Additional Resources ManyInternetandwebdevelopmenttoolsareavailable.WewroteAJAX,RichInternetAp- plicationsandWebDevelopmentforProgrammersusingInternetExplorer7,Firefox2and other free-for-download software. Links to additional resources and software downloads areavailableinourInternetandWebprogrammingrelatedResourceCenters: www.deitel.com/resourcecenters.html/ andatthewebsiteforthisbook: www.deitel.com/books/ajaxfp/ Deitel® Buzz Online Free E-mail Newsletter Each week, the free Deitel® Buzz Online newsletter announces our latest Resource Cen- ter(s)andincludescommentaryonindustrytrendsanddevelopments,linkstofreearticles and resources from our published books and upcoming publications, product-release schedules,errata,challenges,anecdotes,informationonourcorporateinstructor-ledtrain- ingcoursesandmore.It’salsoagoodwayforyoutokeeppostedaboutissuesrelatedto AJAX,RichInternetApplicationsandWebDevelopmentforProgrammers.Tosubscribe,visit www.deitel.com/newsletter/subscribe.html The Deitel Online Resource Centers Our website, www.deitel.com, provides scores ofResource Centerson varioustopics in- cluding programming languages, software, Web 2.0, Internet business and open source projects(Fig.3).TheResourceCentershaveevolvedoutoftheresearchwedotosupport ourbooksandbusinessendeavors.We’vefoundmanyexceptionalresourcesincludingtu- torials,documentation,softwaredownloads,articles,blogs,podcasts,videos,codesamples, books,e-booksandmore.Mostofthemarefree.InthespiritofWeb2.0,wesharethese resources with the worldwide community. Each week we announce our latest Resource CentersintheDeitel®BuzzOnline(www.deitel.com/newsletter/subscribe.html). Acknowledgments Itisagreatpleasuretoacknowledgetheeffortsofmanypeoplewhosenamesmaynotap- pearonthecover,butwhosehardwork,cooperation,friendshipandunderstandingwere crucialtotheproductionofthebook.ManypeopleatDeitel&Associates,Inc.devoted longhourstothisproject—thanksespeciallytoAbbeyDeitelandBarbaraDeitel. We’dalsoliketothanktheparticipantsinourHonorsInternshipprogramwhocon- tributed to this publication—Ilana Segall, a mathematical and computational science majoratStanfordUniversity;JenniferFredholm,anEnglishandcomputersciencemajor atNewYorkUniversity;ScottWehrwein,acomputersciencemajoratMiddleburyCol- lege;MarkKagan,acomputerscience,economicsandmathmajoratBrandeisUniversity; AndrewFaden,acomputerengineeringmajoratNortheasternUniversity;JessicaHenkel, a psychology major and business minor at Northeastern University; and Kyle Banks, a computerscienceandbusinessmajoratNortheasternUniversity.
Description: