D e i t e l ® S e rHow To Program Series Internet & World Wide Web How to Program, 4/E Java How to Program, 7/E C++ How to Program, 6/E C How to Program, 5/E Visual Basic®2005 How to Pro
Trang 2AJAX, Rich Internet
Applications, and
Web Development
For Programmers
Download from Library of Wow! eBook www.wowebook.com
Trang 3D e i t e l ® S e r
How To Program Series
Internet & World Wide Web How to Program, 4/E
Java How to Program, 7/E
C++ How to Program, 6/E
C How to Program, 5/E
Visual Basic®2005 How to Program, 3/E
Visual C#®2005 How to Program, 2/E
Small Java™How to Program, 6/E
Small C++ How to Program, 5/E
Advanced Java™2 Platform How to Program
XML How to Program
Visual C++®.NET How to Program
Perl How to Program
Python How to Program
Deitel Developer Series
AJAX, Rich Internet Applications andWeb Development for ProgrammersC# for Programmers, 2/E
Visual Basic 2005 for Programmers, 2/E
Trang 4i e s P a g e
SafariX Web Books
www.deitel.com/books/SafariX.html
C++ How to Program, 5/E & 6/E
Java How to Program, 6/E & 7/E
Simply C++: An Application-Driven
Tutorial Approach
Simply Visual Basic 2005: An
Application-Driven Tutorial Approach, 2/E
Small C++ How to Program, 5/ESmall Java How to Program, 6/EVisual Basic 2005 How to Program, 3/EVisual C# 2005 How to Program, 2/E
To follow the Deitel publishing program, please register for the free Deitel ® Buzz Online e-mail newsletter at:
www.deitel.com/newsletter/subscribe.html
To communicate with the authors, send e-mail to:
deitel@deitel.comFor information on corporate on-site seminars offered by Deitel & Associates, Inc.worldwide, visit:
www.deitel.com/training/
or write to
deitel@deitel.comFor continuing updates on Prentice Hall/Deitel publications visit:
www.deitel.com www.prenhall.com/deitel www.InformIT.com/deitelCheck out our Resource Centers for valuable web resources that will help you masterC++, other important programming languages, software and Web 2.0 topics:www.deitel.com/ResourceCenters.html
Trang 5been printed with initial capital letters or in all capitals.
The authors and publisher have taken care in the preparation of this book, but make no expressed or implied warranty
of any kind and assume no responsibility for errors or omissions No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein.
The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales, which may include electronic versions and/or custom covers and content particular to your business, training goals, marketing focus, and branding interests For more information, please contact:
U S Corporate and Government Sales
Visit us on the Web: www.phptr.com
Library of Congress Cataloging-in-Publication Data
On file
© 2008 Pearson Education, Inc.
All rights reserved Printed in the United States of America This publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmis- sion in any form or by any means, electronic, mechanical, photocopying, recording, or likewise For information re- garding permissions, write to:
Pearson Education, Inc
Rights and Contracts Department
501 Boylston Street, Suite 900
Boston, MA 02116
Fax (617) 671-3447
ISBN 0-13-158738-2
Text printed in the United States on recycled paper at R.R Donnelley in Crawfordsville, Indiana.
First printing, January 2008
Trang 6AJAX, Rich Internet
Deitel & Associates, Inc.
Upper Saddle River, NJ • Boston • Indianapolis • San Francisco New York • Toronto • Montreal • London • Munich • Paris • Madrid Capetown • Sydney • Tokyo • Singapore • Mexico City
Trang 7Associates, Inc.
Adobe, Dreamweaver, Flex and Flash are either registered trademarks or trademarks of Adobe Systems, Inc.
Apache is a trademark of The Apache Software Foundation.
CSS, DOM, XHTML and XML are registered trademarks of the World Wide Web sortium.
Con-Del.icio.us and Flickr are trademarks of Yahoo! Inc.
Digg is a trademark of Digg Inc.
Firefox is a registered trademark of the Mozilla Foundation.
Google is a trademark of Google, Inc.
JavaScript, Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc in the United States and other countries.
Microsoft, Internet Explorer, Silverlight and the Windows logo are either registered marks or trademarks of Microsoft Corporation in the United States and/or other countries MySpace is a registered trademark of MySpace.com.
trade-UNIX is a registered trademark of The Open Group.
Ruby on Rails is a trademark of David Heinemeier Hansson.
MySQL is a registered trademark of MySQL AB.
Second Life is a registered trademark of Linden Research, Inc.
Skype is a trademark of eBay, Inc.
Web 2.0 is a service mark of CMP Media.
Wikipedia is a registered trademark of WikiMedia.
Throughout this book, trademarks are used Rather than put a trademark symbol in every occurrence of a trademarked name, we state that we are using the names in an editorial fashion only and to the benefit of the trademark owner, with no intention of infringement
of the trademark.
Trang 8To Jesse James Garrett:
For recognizing that "something special was in the air"in web applications development; for coining the term "Ajax"
(Asynchronous JavaScript and XML) to name that phenomenon; and for your tireless efforts in promoting Ajax—
a key set of technologies defining Web 2.0.
Paul and Harvey Deitel
Trang 9Our Resource Centers focus on the vast amounts of free content available online Find resources,downloads, tutorials, documentation, books, e-books, journals, articles, blogs, RSS feeds and more
on many of today’s hottest programming and technology topics For the most up-to-date list of ourResource Centers, visit:
www.deitel.com/ResourceCenters.html
Let us know what other Resource Centers you’d like to see! Also, please register for the free Deitel ®
Buzz Online e-mail newsletter at:
Visual Studio Team tem
Sys-Web 3D Technologies Web Services Windows Presentation Foundation XHTML XML
Games and Game Programming
Computer Game gramming Computer Games Mobile Gaming Sudoku
Pro-Internet Business
Affiliate Programs Competitive Analysis Facebook Social Ads Google AdSense Google Analytics Google Services Internet Advertising Internet Business Initiative Internet Public Relations Link Building Location-Based Services Online Lead Generation Podcasting
Search Engine tion
Optimiza-Selling Digital Content Sitemaps
Web Analytics Website Monetization YouTube and AdSense
Java
Java Java Certification and Assessment Testing Java Design Patterns Java EE 5 Java SE 6
Java SE 7 (Dolphin) Resource Center JavaFX
Microsoft
ASP.NET ASP.NET 3.5 ASP.NET Ajax C#
DotNetNuke (DNN) Internet Explorer 7 (IE7) Microsoft LINQ NET
.NET 3.0 NET 3.5 SharePoint Silverlight Visual Basic Visual C++
Visual Studio Team System Windows Presentation Foundation Windows Vista Microsoft Popfly
Open Source &
LAMP Stack
Apache DotNetNuke (DNN) Eclipse
Firefox Linux MySQL Open Source Perl PHP Python Ruby
Software
Apache DotNetNuke (DNN) Eclipse
Firefox Internet Explorer 7 (IE7) Linux
MySQL Open Source
Search Engines SharePoint Skype Web Servers Wikis Windows Vista
Web 2.0
Alert Services Attention Economy Blogging
Building Web Communities Community Generated Content
Facebook Developer Platform Facebook Social Ads Google Base Google Video Google Web Toolkit (GWT) Internet Video Joost Location-Based Services Mashups
Microformats Recommender Systems RSS
Social Graph Social Media Social Networking Software as a Service (SaaS)
Virtural Worlds Web 2.0 Web 3.0 Widgets
Dive Into Web 2.0 eBook
Web 2 eBook
Other Topics
Computer Games Computing Jobs Gadgets and Gizmos Ring Tones Sudoku
Trang 114.2 Simple Program: Displaying a Line of Text in a Web Page 133
Trang 12Contents xi
5.7 Formulating Algorithms: Sentinel-Controlled Repetition 163
Trang 1412.8 Extensible Stylesheet Language and XSL Transformations 376
Trang 1514.5 Creating Special Effects with Flash 473
14.5.2 Creating an Advertisement Banner with Masking 474
15.14 ActionScript 3.0 Elements Introduced in This Chapter 516
16.8 Connection Independent RIAs on the Desktop:
Trang 16Contents xv
17.6.1 Microsoft Internet Information Services (IIS) 5.1 and 6.0 57617.6.2 Microsoft Internet Information Services (IIS) 7.0 579
Trang 1720 Ruby on Rails 652
21.2.3 Relationship Between an ASPX File and a Code-Behind File 706
21.2.5 Examining the XHTML Generated by an ASP.NET Application 707
21.5.1 Building a Web Form That Displays Data from a Database 75421.5.2 Modifying the Code-Behind File for the Guestbook Application 763
21.6.1 Examining the Completed Secure Books Database Application 76521.6.2 Creating the Secure Books Database Application 769
Trang 18Contents xvii
22.3 Creating and Running a Simple Application in Netbeans 803
22.3.4 Relationship Between the JSP and Page Bean Files 81122.3.5 Examining the XHTML Generated by a Java Web Application 811
22.4.2 Validation Using Validator Components and Custom Validators 825
23.2.1 Building a Web Application That Displays Data from a Database 86023.2.2 Modifying the Page Bean File for theAddressBookApplication 869
23.4.2 JSP File with Virtual Forms and anAutoComplete Text Field 87523.4.3 Providing Suggestions for anAutoComplete Text Field 879
23.5.4 Page Bean That Displays a Map in theMap ViewerComponent 887
24.3 Creating, Publishing, Testing and Describing a Web Service 89424.3.1 Creating a Web Application Project and Adding a
24.3.2 Defining theHugeIntegerWeb Service in Netbeans 89524.3.3 Publishing theHugeIntegerWeb Service from Netbeans 900
Trang 1924.3.4 Testing theHugeIntegerWeb Service with Sun Java
24.3.5 Describing a Web Service with the Web Service
24.4.1 Creating a Client in Netbeans to Consume theHugeInteger
24.7 Consuming a Database-Driven Web Service from a Web Application 93124.7.1 Configuring Java DB in Netbeans and Creating the
24.7.2 Creating a Web Application to Interact with the
24.8 Passing an Object of a User-Defined Type to a Web Service 939
Trang 20… the challenges are for the designers of these applications: to forget what we think we know about the limitations of the Web, and begin to imagine a wider, richer range of possibilities It’s going to be fun.
—Jesse James Garrett, Adaptive Path
“Ajax: A New Approach to Web Applications”
(adaptivepath.com/ideas/essays/archives/000385.php)
Introduction
Welcome to Internet and web programming and Web 2.0! And welcome to a walkthrough
of the Web 2.0 phenomenon from the technical, business and social perspectives We’veworked hard to create what we hope you’ll find to be an informative, entertaining andchallenging learning experience At Deitel & Associates, we write programming languageprofessional books and textbooks for Prentice Hall, deliver corporate training worldwideand develop Web 2.0 Internet businesses This book reflects today’s Web 2.0, Ajax-based,Rich Internet Application-development methodologies
The technologies you’ll learn here are appropriate for experienced professionals whobuild substantial information systems You’ll find “industrial-strength” code examples
We have attempted to write in a clear and straightforward manner using best practices.Perhaps most important, the book presents hundreds of working code examples andshows the outputs produced when these examples are rendered in browsers or run on com-puters We present all concepts in the context of complete working programs We call thisthe “live-code approach.” All of the source code is available for download from
pro-Today’s users are accustomed to desktop applications with rich graphical user faces (GUIs), such as those used on Apple’s Mac OS X systems, Microsoft Windows sys-tems, various Linux systems and more Users want applications that employ the
inter-Preface
Trang 21multimedia capabilities of graphics, images, animation, audio and video They want 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 theirbusiness and personal data They want applications that are not limited to the desktop oreven to some local computer network, but that can integrate Internet and web compo-nents, and remote databases Programmers want to use all these capabilities in a truly por-table manner so that applications will run without modification on a variety of platforms.
appli-In this book, we present a number of powerful software technologies that will enableyou to build these kinds of systems Early in the book we focus on building the portions
of web-based applications that reside on the client side (i.e., the portions of applicationsthat typically run in web browsers such as Mozilla’s Firefox or Microsoft’s InternetExplorer), using technologies such as the XHTML, JavaScript, CSS, Flash, Flex andExtensible Markup Language (XML) Later in the book we concentrate on using technol-ogies such as web servers, databases, PHP, Ruby on Rails, ASP.NET, ASP.NET Ajax andJavaServer Faces (JSF) to build the server side of web-based applications These portions
of applications typically run on “heavy-duty” computer systems on which organizations’business-critical websites reside By mastering the technologies in this book, you’ll be able
to build substantial web-based, client/server, database-intensive, “multitier” applications
If you have questions as you read this book, send an e-mail todeitel@deitel.com—we’ll respond promptly For updates on the book and the status of all supporting software,and for the latest news on Deitel publications and services, visitwww.deitel.com Sign up
atwww.deitel.com/newsletter/subscribe.htmlfor the free Deitel ® Buzz Online e-mail
newsletter and check outwww.deitel.com/ResourceCenters.htmlfor our growing list ofInternet and web programming, Internet business, Web 2.0 and related Resource Centers.Each week we announce our latest Resource Centers in the newsletter
• Focus on Web 2.0 technologies and concepts
• Chapter on Web 2.0 and Internet Business (reviewed by leaders in the Web 2.0community)
• Focus on building Rich Internet Applications with the interactivity of desktopapplications
• Chapter on building Ajax-enabled web applications with “raw” Ajax and with theDojo JavaScript libraries Applications in this chapter demonstrate partial-pageupdates and type-ahead capabilities
• Chapter on Adobe Flex—a Rich Internet Application framework for creatingscalable, cross-platform, multimedia-rich applications for delivery within the en-terprise or across the Internet
Trang 22Architecture xxi
• Chapter on rapid applications development of database-driven web applicationswith Ruby on Rails; also discusses developing Ajax applications with the Proto-type and Script.aculo.us libraries
• Two chapters on Adobe Flash CS3, including building a computer game
• Significant treatment of client-side scripting with JavaScript
• Significant treatments of XHTML DOM manipulation and JavaScript events
• Significant treatment of XML DOM manipulation with JavaScript
• Chapter on building SOAP-based web services with Java and REST-based webservices with ASP.NET (using Visual Basic)
• Chapter on PHP 5
• Coverage of ASP.NET, featuring ASP.NET Ajax
• JavaServer Faces (JSF) coverage emphasizing building Ajax-enabled JSF tions
applica-• Client-side case studies that enable you to interact with preimplemented side applications and web services that we host attest.deitel.com
server-• Case studies including Deitel Cover Viewer (JavaScript/DOM), Address Book(Ajax), Cannon Game (Flash), Weather/Yahoo! Maps Mashup (Flex), MailingList (PHP/MySQL), Message Forum and Flickr Photo Viewer (Ruby on Rails),Guest Book and Secure Books Database (ASP.NET), Address Book with GoogleMaps (JavaServer Faces) and Blackjack (JAX-WS web services)
All of this has been carefully reviewed by a team of 38 distinguished industry developersand academics
AJAX, Rich Internet Applications and Web Development for
Programmers Architecture
This book focuses on Web 2.0 and Rich Internet Application (RIA) development Ourgoal is to develop webtop applications that have the responsiveness, look and feel of tradi-tional desktop applications Deitel & Associates, Inc has evolved into a development or-ganization, while continuing its focus on programming languages textbook andprofessional book authoring, and corporate training We’re building the infrastructure forthe Internet businesses we’re designing and developing as part of our Web 2.0 InternetBusiness Initiative This book includes discussions of many practical issues we’ve encoun-tered in developing that infrastructure
Figure 1 shows the architecture of AJAX, Rich Internet Applications and Web
Develop-ment for Programmers The book is divided into several parts Chapter 1 introduces Web
2.0 from the technical, business and social perspectives, and provides a foundation forunderstanding Rich Internet Application development If you are a serious web developer,you’ll want to test your web applications across many browsers and platforms The exam-ples for the book execute correctly on both Microsoft’s Internet Explorer 7 (IE7) andMozilla’s Firefox 2 (FF2) browsers Most of the examples will also work in other browserssuch as Opera and Safari, but may not work on earlier browsers Microsoft Windows usersshould upgrade to IE7 and install Firefox; readers with other operating systems shouldinstall Firefox
Trang 23The second part of the book, Chapters 2–13, presents a detailed treatment of Ajaxcomponent technologies, including a comprehensive treatment of JavaScript that spansnine chapters and concludes with Chapter 13’s treatment of Ajax development Ajax is not
a new technology—we’ve been writing about all but one of its component technologiessince 1999, and many of the technologies existed before that However, Ajax is one of thekey technologies of Web 2.0 and RIAs Chapters 2–13 cover “raw” Ajax programming,where you’ll handle the details yourself—several later chapters in the book demonstratetechnologies that encapsulate Ajax functionality to help you easily build Ajax-based appli-cations that operate across a wide variety of browsers and browser versions without yourhaving to be concerned with the low-level details
The third part of the book, Chapters 13–24, focuses on both the client and serversides of the GUI and the graphical part of RIA development Here we cover client-sidetechnologies such as Adobe Flash and Adobe Flex that use, or can be combined with, Ajax
or Ajax-like capabilities to develop RIAs Each of these technologies also can consume webservices Next, we present the server side of web application development with discussions
of web servers (IIS and Apache), databases, server-side scripting languages such as PHPand 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 bothSOAP-based and REST-based web services
You may have noticed that Chapter 13, Ajax-Enabled Rich Internet Applications,overlaps the second and third parts of the book Chapter 13 serves as a bridge from “raw”Ajax development to “encapsulated” Ajax development with the Dojo libraries
3 Cascading Style Sheets™ (CSS)
4 JavaScript: Introduction to Scripting
5 JavaScript: Control Statements I
6 JavaScript: Control Statements II
7 JavaScript: Functions
8 JavaScript: Arrays
9 JavaScript: Objects
10 DOM: Object Model and Collections
11 JavaScript: Event Model
12 XML and RSS
13 Ajax-Enabled Rich Internet Applications
14 Adobe® Flash® CS3
15 Adobe® Flash® CS3: Building an Interactive Game
16 Adobe® Flex™ 2 and Rich Internet Applications
17 Web Servers (IIS and Apache)
18 Database: SQL, MySQL, ADO.NET 2.0, Java DB
19 PHP
20 Ruby on Rails
21 ASP.NET 2.0 and ASP.NET Ajax
22 JavaServer™ Faces (JSF) Web Applications
23 Ajax-Enabled JSF Web Applications
Trang 24Dependency Chart xxiii
Dependency Chart
Figure 2 illustrates the dependencies that exist among chapters in the book An arrowpointing into a chapter indicates that it depends on the content of the chapter from whichthe arrow points For example, Chapter 24, Web Services, depends on both Chapters 21and 23 We recommend that you read all of a given chapter’s dependencies before readingthat chapter, though other orders are possible We’ve also commented on some additionaldependencies in the diagram’s footnotes
Teaching Approach
AJAX, Rich Internet Applications and Web Development for Programmers contains a rich
col-lection of examples The book concentrates on the principles of good software engineeringand stresses program clarity We are educators who teach leading-edge topics in industryclassrooms worldwide Dr Harvey M Deitel has 20 years of college teaching experienceand 18 years of industry teaching experience Paul Deitel has 16 years of industry teachingexperience The Deitels have taught courses at all levels to government, industry, militaryand academic clients of Deitel & Associates
Live-Code Approach AJAX, Rich Internet Applications and Web Development for
Program-mers is loaded with “live-code” examples—each new concept is presented in the context of
a complete working web application that is immediately followed by one or more screencaptures showing the application’s functionality This style exemplifies the way we teachand write about programming; we call this the “live-code approach.”
Syntax Shading We syntax shade all the code, similar to the way most
integrated-devel-opment environments and code editors syntax color code This improves code ty—an important goal, given that this book contains about 18,000 lines of code incomplete, working programs Our syntax-shading conventions are as follows:
readabili-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
Code Highlighting We place white rectangles around each program’s key code segments Using Fonts for Emphasis We place the key terms and the index’s page reference for each
defining occurrence in bold italic text for easier reference We emphasize on-screen
com-ponents in thebold Helveticafont (e.g., theFilemenu) and emphasize program text in theLucidafont (e.g.,int x = 5)
Web Access All of the source-code examples for AJAX, Rich Internet Applications and Web
Development for Programmers are available for download from:
www.deitel.com/books/ajaxfp/
Site registration is quick, easy and free Download all the examples, then run each program
as you read the corresponding text discussions Making changes to the examples and seeingthe effects of those changes is a great way to enhance your Internet and web programminglearning experience
Trang 25Fig 2 | AJAX, Rich Internet Applications and Web Development for Programmers chapter
dependency chart
Part 2: Client-Side Rich Internet Applications and Ajax
Part 4: Rich Internet
21 ASP.NET and ASP.NET Ajax
22 Java Server Faces (JSF) 1
23 Ajax-Enabled JSF Applications 1
24 Web Services 2
1 Chapters 22–23 require knowledge of Java Standard Edition 6.
2 Sections 24.2–24.8 require Chapters 22–22 Section 24.9 requires Chapter 21.
Part 1: Introduction
2 Introduction to XHTML
3 Cascading Style Sheets (CSS)
4 JavaScript: Introduction to Scripting
5 JavaScript: Control Statements I
6 JavaScript: Control Statements II
Trang 26Teaching Approach xxv
Objectives Each chapter begins with a statement of objectives This lets you know what
to expect and gives you an opportunity to determine if you have met the objectives afterreading the chapter
Quotations The learning objectives are followed by quotations Some are humorous;
some are philosophical; others offer interesting insights We hope that you enjoy relatingthe quotations to the chapter material
Outline The chapter outline helps you approach the material in a top-down fashion, so
you can anticipate what is to come and set a comfortable learning pace
Illustrations/Figures Abundant charts, tables, line drawings, programs and program
out-put are included
Programming Tips We include programming tips to help you focus on important aspects
of program development These tips and practices represent the best we have gleaned from
a combined six decades of programming and teaching experience One of our readers told
us that she feels this approach is like the highlighting of axioms, theorems and corollaries
in mathematics books—it provides a basis on which to build good software
Good Programming Practices
Good Programming Practices call attention to techniques that will help you produce programs that are clearer, more understandable and more maintainable. 3.0
Common Programming Errors
Programmers tend to make certain kinds of errors frequently Pointing out these Common gramming Errors reduces the likelihood that you’ll make the same mistakes. 3.0
Pro-Error-Prevention Tip
These tips contain suggestions for exposing bugs and removing them from your programs; many describe aspects of programming that prevent bugs from getting into programs in the first place.3.0
Performance Tip
These tips highlight opportunities for making your programs run faster or minimizing the
Portability Tip
We include Portability Tips to help you write code that will run on a variety of platforms and
to explain how to achieve a high degree of portability. 3.0
Software Engineering Observation
The Software Engineering Observations highlight architectural and design issues that affect the construction of software systems, especially large-scale systems. 3.0
Thousands of Index Entries We have included an extensive index which is especially useful
when you use the book as a reference
“Double Indexing” of Live-Code Examples For every source-code program in the book,
we index the figure caption both alphabetically and as a subindex item under “Examples.”This makes it easier to find examples using particular features
Trang 27AJAX, Rich Internet Applications and Web Development for
Programmers Software Downloads and Additional Resources
Many Internet and web development tools are available We wrote AJAX, Rich Internet
Ap-plications and Web Development for Programmers using Internet Explorer 7, Firefox 2 and
other free-for-download software Links to additional resources and software downloadsare available in our Internet and Web programming related Resource Centers:
www.deitel.com/resourcecenters.html/
and at the website for this book:
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) and includes commentary on industry trends and developments, links to free articlesand resources from our published books and upcoming publications, product-releaseschedules, errata, challenges, anecdotes, information on our corporate instructor-led train-ing courses and more It’s also a good way for you to keep posted about issues related to
AJAX, Rich Internet Applications and Web Development for Programmers To subscribe, visit
www.deitel.com/newsletter/subscribe.html
The Deitel Online Resource Centers
Our website,www.deitel.com, provides scores of Resource Centers on various topics cluding programming languages, software, Web 2.0, Internet business and open sourceprojects (Fig 3) The Resource Centers have evolved out of the research we do to supportour books and business endeavors We’ve found many exceptional resources including tu-torials, documentation, software downloads, articles, blogs, podcasts, videos, code samples,books, e-books and more Most of them are free In the spirit of Web 2.0, we share theseresources with the worldwide community Each week we announce our latest Resource
in-Centers in the Deitel ® Buzz Online (www.deitel.com/newsletter/subscribe.html)
Acknowledgments
It is a great pleasure to acknowledge the efforts of many people whose names may not pear on the cover, but whose hard work, cooperation, friendship and understanding werecrucial to the production of the book Many people at Deitel & Associates, Inc devotedlong hours to this project—thanks especially to Abbey Deitel and Barbara Deitel.We’d also like to thank the participants in our Honors Internship program who con-tributed to this publication—Ilana Segall, a mathematical and computational sciencemajor at Stanford University; Jennifer Fredholm, an English and computer science major
ap-at New York University; Scott Wehrwein, a computer science major ap-at Middlebury lege; Mark Kagan, a computer science, economics and math major at Brandeis University;Andrew Faden, a computer engineering major at Northeastern University; Jessica Henkel,
Col-a psychology mCol-ajor Col-and business minor Col-at NortheCol-astern University; Col-and Kyle BCol-anks, Col-acomputer science and business major at Northeastern University
Trang 28Code Search Engines
and Code Sites
Internet Business
Affiliate Programs Competitive Analysis Facebook Social Ads Google AdSense Google Analytics Google Services Internet Advertising Internet Business Initiative Internet Public Relations Link Building Location-Based Services Online Lead Generation Podcasting Search Engine Optimization Selling Digital Content Sitemaps Web Analytics Website Monetization YouTube and AdSense
Java
Java Java Certification and Assessment Testing Java Design Patterns
Java EE 5 Java SE 6 Java SE 7 (Dolphin) Resource Center JavaFX
Microsoft
ASP.NET ASP.NET 3.5 ASP.NET Ajax C#
DotNetNuke (DNN) Internet Explorer 7 (IE7)
Microsoft LINQ NET
.NET 3.0 NET 3.5 SharePoint Silverlight Visual Basic Visual C++
Visual Studio Team System
Windows Presentation Foundation Windows Vista Microsoft Popfly
Open Source &
LAMP Stack
Apache DotNetNuke (DNN) Eclipse
Firefox Linux MySQL Open Source Perl PHP Python Ruby
Software
Apache DotNetNuke (DNN) Eclipse
Firefox Internet Explorer 7 (IE7)
Linux
MySQL Open Source Search Engines SharePoint Skype Web Servers Wikis Windows Vista
Web 2.0
Alert Services Attention Economy Blogging
Building Web Communities Community Generated Content Facebook Developer Platform Facebook Social Ads Google Base Google Video Google Web Toolkit (GWT)
Internet Video Joost
Location-Based Services Mashups Microformats Recommender Systems RSS Social Graph Social Media Social Networking Software as a Service (SaaS)
Virtural Worlds Web 2.0 Web 3.0 Widgets
Dive Into Web 2.0 eBook
Other Topics
Computer Games Computing Jobs Gadgets and Gizmos Ring Tones Sudoku
Fig 3 | Deitel Resource Centers atwww.deitel.com/resourcecenters.html
Trang 29We are fortunate to have worked on this project with the talented and dedicated team
of publishing professionals at Prentice Hall We appreciate the extraordinary efforts ofMarcia Horton, Editorial Director of Prentice Hall’s Engineering and Computer ScienceDivision, Mark Taub, Editor-in-Chief of Prentice Hall Professional, and John Fuller,Managing Editor of Prentice Hall Professional Carole Snyder and Dolores Mars did aremarkable job recruiting the book’s large review team and managing the review process.Sandra Schroeder and Chuti Prasertsith did a wonderful job designing the book’s cover.Bob Engelhardt and Marta Samsel did a marvelous job managing the book’s production
This book was adapted from our book Internet & World Wide Web How to Program,
4/e We wish to acknowledge the efforts of our reviewers on that book Adhering to a tight
time schedule, they scrutinized the text and the programs, providing countless suggestionsfor improving the accuracy and completeness of the presentation
Reviewers
Roland Bouman (MySQL AB), Peter Brandano (KoolConnect Technologies, Inc.), MattChotin (Adobe), Chris Cornutt (PHPDeveloper.org), Phil Costa (Adobe), Umachitra Da-modaran (Sun Microsystems), Vadiraj Deshpande (Sun Microsystems), Justin Erenkrantz(The Apache Software Foundation), Christopher Finke (Netscape), Jesse James Garrett(Adaptive Path), Kevin Henrikson (Zimbra.com), Tim Heuer (Microsoft), Molly E.Holtzschlag (W3C), Ralph Hooper (University of Alabama, Tuscaloosa), Johnvey Hwang(Splunk, Inc.), Joe Kromer (New Perspective and the Pittsburgh Adobe Flash UsersGroup), Eric Lawrence (Microsoft), Billy B L Lim (Illinois State University), ShobanaMahadevan (Sun Microsystems), Patrick Mineault (Freelance Flash Programmer), AnandNarayanaswamy (Microsoft), John Peterson (Insync and V.I.O., Inc.), Jennifer Powers(University of Albany), Robin Schumacher (MySQL AB), José Antonio González Seco(Parlamento de Andalucia), Dr George Semeczko (Royal & SunAlliance Insurance Can-ada), Steven Shaffer (Penn State University), Tim Sneath (Microsoft), Karen Tegtmeyer(Model Technologies, Inc.), Paul Vencill (MITRE), Raymond Wen (Microsoft), Eric M.Wendelin (Auto-trol Technology Corporation), Raymond F Wisman (Indiana Universi-ty) and Daniel Zappala (Brigham Young University)
Well, there you have it! We hope you enjoy this look at the exciting world of Ajax,Rich Internet Applications and web development in a Web 2.0 world As you read thebook, we would sincerely appreciate your comments, criticisms, corrections and sugges-tions for improving the text Please address all correspondence to:
deitel@deitel.com
We’ll respond promptly, and post corrections and clarifications at:
www.deitel.com/books/ajaxfp/
We hope you enjoy reading Ajax, Rich Internet Applications and Web Development for
Pro-grammers as much as we enjoyed writing it!
Paul J Deitel
Dr Harvey M Deitel
Maynard, Massachusetts
Trang 30About the Authors xxix
About the Authors
Paul J Deitel, CEO and Chief Technical Officer of Deitel & Associates, Inc., is a graduate
of MIT’s Sloan School of Management, where he studied Information Technology Heholds the Java Certified Programmer and Java Certified Developer certifications, and hasbeen designated by Sun Microsystems as a Java Champion Through Deitel & Associates,Inc., he has delivered Internet and web programming, Java, C, C++, C# and Visual Basiccourses to industry clients, including IBM, Sun Microsystems, Dell, Lucent Technologies,Fidelity, NASA at the Kennedy Space Center, the National Severe Storm Laboratory,White Sands Missile Range, Rogue Wave Software, Boeing, Stratus, Cambridge Technol-ogy Partners, Open Environment Corporation, One Wave, Hyperion Software, Adra Sys-tems, Entergy, CableData Systems, Nortel Networks, Puma, iRobot, Invensys and manymore He has also lectured on Java and C++ for the Boston Chapter of the Association forComputing Machinery He and his father, Dr Harvey M Deitel, are the world’s best-sell-ing programming language textbook authors
Dr Harvey M Deitel, Chairman and Chief Strategy Officer of Deitel & Associates,
Inc., has 46 years of experience in the computer field Dr Deitel earned B.S and M.S.degrees from MIT and a Ph.D from Boston University He has 20 years of college teachingexperience, including earning tenure and serving as the Chairman of the Computer ScienceDepartment at Boston College before founding Deitel & Associates, Inc., with his son,Paul J Deitel He and Paul are the co-authors of several dozen books and multimedia pack-ages and they are writing many more With translations published in Japanese, German,Russian, Spanish, Traditional Chinese, Simplified Chinese, Korean, French, Polish,Italian, Portuguese, Greek, Urdu and Turkish, the Deitels’ texts have earned internationalrecognition Dr Deitel has delivered hundreds of professional seminars to major corpora-tions, academic institutions, government organizations and the military
About Deitel & Associates, Inc.
Deitel & Associates, Inc., is an internationally recognized corporate training and creation organization specializing in computer programming languages, Internet and websoftware technology, object technology education and Internet business developmentthrough its Web 2.0 Internet Business Initiative The company provides instructor-ledcourses on major programming languages and platforms, such as C++, Java, C, C#, VisualC++, Visual Basic, XML, object technology and Internet and web programming Thefounders of Deitel & Associates, Inc are Paul J Deitel and Dr Harvey M Deitel Thecompany’s clients include many of the world’s largest companies, government agencies,branches of the military, and academic institutions Through its 32-year publishing part-nership with Prentice Hall, Deitel & Associates, Inc publishes leading-edge programming
content-professional books, textbooks, interactive multimedia Cyber Classrooms, Complete Training
Courses, web-based training courses, online and offline LiveLessons video courses, and
e-content for the popular course management systems WebCT, Blackboard and Pearson’sCourseCompass Deitel & Associates, Inc., and the authors can be reached via e-mail at:deitel@deitel.com
To learn more about Deitel & Associates, Inc., its publications and its worldwide
Dive Into ®Series Corporate Training curriculum, visit:
Trang 31U S Corporate and Government Sales
Trang 32Please follow these instructions to download the book’s examples and ensure you have acurrent web browser before you begin using this book.
Downloading the Ajax, Rich Internet Applications and Web
Devel-opment for Programmers Source Code
The source code in Ajax, Rich Internet Applications and Web Development for Programmers
can be downloaded as a ZIP archive file fromwww.deitel.com/books/ajaxfp/ After youregister and log in, click the link for the examples underDownload Code Examples and Other Premium Content for Registered Users Extract the example files to your hard diskusing a ZIP file extractor program, such as WinZip (www.winzip.com) On Windows, wesuggest that you extract the files to a folder such asC:\ajaxfp_examples On Mac OS Xand Linux, we suggest that you extract the files to a folder namedajaxfp_examplesin
your home folder [Note: If you are working in a computer lab, ask your instructor where
you can save the example code.]
Web Browsers Used in This Book
We’ve tested every example in this book using Mozilla’s Firefox 2 and Microsoft’s InternetExplorer 7 web browsers Before you begin, ensure that you have one or both of thesebrowsers installed on your computer Internet Explorer 7 is available only for MicrosoftWindows operating systems If you are a Windows user and do not have Internet Explorer
7, you can download it fromwww.update.microsoft.com using Microsoft’s WindowsUpdate service Firefox 2 is available for most platforms You can download Firefox 2 fromwww.firefox.com
Many of the book’s examples will not work in Internet Explorer 6 Though the
exam-ples in this book may run on other recent web browsers, such as Opera (www.opera.com)
or Apple’s Safari (www.apple.com/safari/), we have not tested the examples on these orany other browsers
You are now ready to begin your web programming studies with Ajax, Rich Internet
Applications and Web Development for Programmers We hope you enjoy the book! If you
have any questions, please feel free to email us at deitel@deitel.com We’ll respondpromptly
Before You Begin
Trang 34Introduction
The renaissance of interest in the web that we call
Web 2.0 has reached the mainstream.
—Tim O’Reilly
Trang 35Dive Into ®
Web 2.0
O B J E C T I V E S
In this chapter you will learn:
■ The defining characteristics of Web 2.0
■ Why search is fundamental to Web 2.0
■ How Web 2.0 empowers the individual
■ The importance of collective intelligence and network
effects
■ The significance and growth of blogging
■ Social networking, social media and social bookmarking
■ How tagging leads to folksonomies
■ How web services enable new applications to be quickly
and easily “mashed up” from existing applications
■ Web 2.0 technologies
■ Web 2.0 Internet business and monetization models
■ The emerging Semantic Web (the “web of meaning”)
Network effects from user butions are the key to market dominance in the Web 2.0 era.
contri-—Tim O’Reilly
Link by link, click by click, search is building possibly the most lasting, ponderous, and sig- nificant cultural artifact in the history of humankind: the Data- base of Intentions.
—John Battelle, The Search Web 2.0 is a massive social ex- periment this is an opportunity
to build a new kind of tional understanding citizen to citizen, person to person.
interna-—Lev Grossman, TIME One of the powerful things about networking technology like the Internet or the Web or the Se- mantic Web is that the things we’ve just done with them far surpass the imagination of the people who invented them.
—Tim Berners-Lee, interviewed
by Peter Moon, IDG Now
Trang 36[Note: Please be sure to read the Preface for an introduction and an overview of the entire
book.] We begin with the principles, applications, technologies, companies, business els and monetization strategies of Web 2.0 When the Mosaic browser was introduced in
mod-1993, the web exploded in popularity It continued to experience tremendous growththroughout the 1990s—a period referred to as the “dot-com bubble”; that bubble burst in
2001 In 2003 there was a noticeable shift in how people and businesses were using the web
and developing web-based applications The term Web 2.0—coined by Dale Dougherty
of O’Reilly ® Media1in 2003 to describe this trend—became a major media buzzword, but
1.12 Rich Internet Applications (RIAs)
1.13 Web Services, Mashups, Widgets and Gadgets
1.14 Location-Based Services
1.15 XML, RSS, Atom, JSON and VoIP
1.16 Web 2.0 Monetization Models
1.17 Web 2.0 Business Models
1.18 Future of the Web
1.19 Where to Go for More Web 2.0 Information
1.20 Web 2.0 Bibliography
1.21 Web 2.0 Glossary
1 O’Reilly, T “What is Web 2.0: Design Patterns and Business Models for the Next Generation of Software.” September 2005 <http://www.oreillynet.com/pub/a/oreilly/tim/news/2005/09/ 30/what-is-web-20.html>
Trang 37few people really know what it means Generally, Web 2.0 companies use the web as a form to create collaborative, community-based sites (e.g., social networking sites, blogs, wi-kis, etc.) Web 2.0 was popularized by the annual O’Reilly Media Web 2.0 Summit(launched in 2004), in Tim O’Reilly’s defining article on Web 2.0 entitled, “What is Web2.0: Design Patterns and Business Models for the Next Generation of Software,”2and inJohn Musser and Tim O’Reilly’s for-sale report, “Web 2.0 Principles and Best Practices.”3The growth of Web 2.0 can be attributed to some key factors First, hardware keepsgetting cheaper and faster, with memory capacities and speeds increasing at a rapid rate.Moore’s Law states that the power of hardware doubles every two years, while the priceremains essentially the same.4 This allows for development of applications with highdemands that would have been previously unthinkable Second, broadband Internet usehas exploded—a Pew Internet study in March 2006 found 42% of American adults hadhigh-speed Internet in their homes Of the 35% of Internet users who had posted contentonline, 73% had broadband Internet.5 The abundance of digital media online wouldnever have been possible without high-speed Internet Third, the availability of abundantopen source software (see Section 1.11) has resulted in cheaper (and often free) customiz-able software options This makes it easier to start new Web 2.0 companies and greatly
plat-decreases the cost of failure Fourth, unlike in Web 1.0 (the state of the web through the
1990s and early 2000s), there are many easy-to-employ models available to monetize Web2.0 businesses—immediately generating (modest amounts of) revenue allows for morestable growth of new companies
Our information on the companies in this chapter comes from common knowledge,the company websites and the footnoted books and articles
1.2 What Is Web 2.0?
In a sense, this entire chapter defines Web 2.0, but let’s begin with a brief, one-section cussion Web 1.0 was focused on a relatively small number of companies and advertisersproducing content for users to access—some people called the web at the time the “bro-
dis-chure web.” Web 2.0 involves the user—not only is the content often created by users, but
users help organize it, share it, remix it, critique it, update it, etc One way to look at Web
1.0 is as a lecture, a small number of professors informing a large audience of students In comparison, Web 2.0 is a conversation, with everyone having the opportunity to speak and
share views
Web 2.0 embraces an architecture of participation—a design that encourages user
interaction and community contributions.6You, the user, are the most important aspect
2 O’Reilly, T “What is Web 2.0: Design Patterns and Business Models for the Next Generation of ware.” September 2005 <http://www.oreillynet.com/pub/a/oreilly/tim/news/2005/09/30/ what-is-web-20.html>
Soft-3. Musser, J and T O’Reilly Web 2.0 Principles and Best Practices O’Reilly Media, Inc., 2006.
4 Moore, G.“Cramming More Components onto Integrated Circuits.”Electronics, April 1965<ftp:/ /download.intel.com/museum/Moores_Law/Articles-Press_Releases/Gordon_Moore _1965_Article.pdf>
5. Horrigan, J B “Home Broadband Adoption 2006.” Pew Internet & American Life Project, May 2006
<http://www.pewinternet.org/pdfs/PIP_Broadband_trends2006.pdf>
6 O’Reilly, T “What is Web 2.0: Design Patterns and Business Models for the Next Generation of ware.” September 2005 <http://www.oreillynet.com/pub/a/oreilly/tim/news/2005/09/30/ what-is-web-20.html>
Trang 38Soft-1.2 What Is Web 2.0? 5
of Web 2.0—so important, in fact, that in 2006, TIME Magazine’s “Person of the Year”
was “you.”7The article recognized the social phenomenon of Web 2.0—the shift awayfrom a powerful few to an empowered many
“We can’t be device centric we must be user centric.”
—Bill Gates, MIX06 conference 8
Many Web 2.0 companies are built almost entirely on user-generated content and
har-nessing collective intelligence The significance is not just in having user-generated
con-tent, but in how it is used Google—the leading search engine and Internet advertisingcompany—sends its users to user-generated websites by considering what users collectivelyhave valued in the past For websites like MySpace®, Flickr™, YouTube and Wikipedia®,
users create the content, while the sites provide the platforms These companies trust their
users—without such trust, users cannot make significant contributions to the sites.
“A platform beats an application every time.”
—Tim O’Reilly 9
The architecture of participation is seen in software development as well Open sourcesoftware is available for anyone to use and modify with few or no restrictions—this hasplayed a major role in Web 2.0 development Harnessing collective intelligence,10com-munities collaborate to develop software that many people believe is better than proprie-tary software
You, the user, are not only contributing content and developing open source software,but you are also directing how media is delivered, and deciding which news and informa-tion outlets you trust Many popular blogs now compete with traditional media power-houses Social bookmarking sites such as del.icio.us and Ma.gnolia allow users torecommend their favorite sites to others Social media sites such as Digg™ or Redditenable the community to decide which news articles are the most significant You are also
changing the way we find the information on these sites by tagging (i.e., labeling) web
content by subject or keyword in a way that helps anyone locate information more tively This is just one of the ways Web 2.0 helps users identify new meaning in alreadyexisting content RSS feeds (Chapter 12, XML and RSS) enable you to receive new infor-mation as it is updated—pushing the content right to your desktop
effec-The rise of social networks has changed the way we interact and network MySpace—
the largest social network—has rapidly become the world’s most popular website Otherpopular social networking sites include Facebook, Bebo, LinkedIn, and Second Life—a
3D virtual world where you interact with others via your online persona called an avatar.
7. Grossman, L “TIME’s Person of the Year: You.” TIME, December 2006<http://www.time.com/ time/magazine/article/0,9171,1569514,00.html>
8. “Bill Gates: Microsoft MIX06 Conference.” Microsoft, March 2006<http://www.microsoft.com/ presspass/exec/billg/speeches/2006/03-20MIX.mspx>
9 O’Reilly, T “What is Web 2.0: Design Patterns and Business Models for the Next Generation of ware.” September 2005 <http://www.oreillynet.com/pub/a/oreilly/tim/news/2005/09/30/ what-is-web-20.html>
10 O’Reilly, T “What is Web 2.0: Design Patterns and Business Models for the Next Generation of ware.” September 2005 <http://www.oreillynet.com/pub/a/oreilly/tim/news/2005/09/30/ what-is-web-20.html>
Trang 39Soft-Many Web 2.0 businesses leverage the Long Tail.11Coined by Chris Anderson in an
article in the October 2004 WIRED magazine, the Long Tail refers to the economic model
in which the market for non-hits (typically large numbers of low-volume items) could besignificant and sometimes even greater than the market for big hits (typically small num-bers of high-volume items).12So an online company like Netflix—which has a catalog ofover 80,000 movie titles for rent—typically rents a large volume of less popular movies inaddition to the substantial business it does renting hits A local movie store has limitedshelf space and serves a small, local population; it cannot afford the space to carry the LongTail movies in every store However, Netflix serves millions of people and does not havethe physical constraints of stores; it can keep a small inventory of many Long Tail movies
to serve its entire customer base The opportunity to leverage the Long Tail is made sible by the relative ease of running a Web 2.0 Internet business and is fueled by the socialeffects of Web 2.0 that increase exposure for lesser-known products
pos-In this chapter, we introduce some of the key technologies used to create Web 2.0applications Many of these technologies are discussed in detail in the programming chap-
ters of Ajax, Rich Internet Applications and Web Development for Programmers You’ll learn
web development technologies, such as Ajax (Chapter 13); its component technologies,including XHTML (Chapter 2), Cascading Style Sheets (CSS, Chapter 3), JavaScript(Chapters 4–9), the Document Object Model (DOM, Chapter 10), XML (Chapter 12)and the XMLHttpRequest object (Chapter 13); and the popular Ajax toolkits—Dojo(Chapter 13) and Script.aculo.us (Chapter 20)
You’ll learn how to build Rich Internet Applications (RIAs)—web applications thatoffer the responsiveness and rich GUI features of desktop applications We discuss keytools for building RIAs, including Adobe’s Flex (Chapter 16), ASP.NET Ajax(Chapter 21) and Sun’s JavaServer Faces (Chapters 22–23) We also discuss other populardevelopment technologies including JSON (Chapter 13), the web servers IIS and Apache(Chapter 17), MySQL (Chapter 18), PHP (Chapter 19), and ASP.NET (Chapter 21)
We discuss the emergence of web services (Chapter 24), which allow you to rate functionality from existing applications into your own applications quickly and easily.For example, using Amazon Web Services™, you can create a specialty bookstore and earnrevenues through the Amazon Associates program; or using Google™ Maps web serviceswith eBay web services, you can build location-based mashup applications to find auctionitems in certain geographical areas Web services, inexpensive computers, abundant high-speed Internet access, open source software and many other elements have inspired new,
incorpo-exciting lightweight business models that people can launch with only a small investment.
Some websites with robust functionality that might have required hundreds of thousands
or even millions of dollars to build in the 1990s can now be built for nominal amounts ofmoney
Section 1.17 overviews key Web 2.0 business models, many of which are alsoexplained in greater depth throughout the chapter Fig 1.1 includes a list of Web 2.0-related conferences Some have a technology focus, while others have a business focus
11 Anderson, C The Long Tail: Why the Future of Business Is Selling Less of More Hyperion, 2006.
12 Anderson, C “The Long Tail.” WIRED, October 2004<http://www.wired.com/wired/archive/ 12.10/tail.html>
Trang 40In Web 2.0, the saying “content is king” remains a prevailing theme With seemingly
end-less content available online, the findability of content becomes key Search engines are
the primary tools people use to find information on the web Today, you perform searcheswith keywords, but the future of web search will use natural language (see, for example,Powerset.com) Currently, when you enter a keyword or phrase, the search engine finds
matching web pages and shows you a search engine results page (SERP) with
recom-mended web pages listed and sorted by relevance People-assisted search engines have alsoemerged, such as Mahalo, which pays people to develop search results.14The popularity
of vertical search engines—ones that focus on a specific topic or industry—is on the rise,though traffic to these search engines is still far behind the major (more generalized) searchengines
Traffic to the major search engines is growing rapidly—according to a recent Score (a web analytics company) report, Americans conducted 8 billion search queries inJune 2007, up 26% from the previous year In the same report, the comScore analysis ofU.S market share across the most popular search engines reported Google at the top with49.5% of the U.S search market, followed by Yahoo! with 25.1%, Microsoft with 13.2%,Ask with 5.0% and Time Warner Network with 4.2%.15
com-Web 2.0 and related conferences
Search Engine StrategiesTools of Change for PublishingUbuntu Live
Web 2.0 ExpoWeb 2.0 SummitWhere 2.0
Fig 1.1 | Web 2.0 and related conferences
13 “Company Overview.” Google<http://www.google.com/intl/en/corporate/index.html>
14 “Mahalo Greenhouse FAQ.” Mahalo <http://greenhouse.mahalo.com/Mahalo_Greenhouse _FAQ>
15 “comScore Releases June U.S Search Engine Rankings.” CNNMoney, 16 July 2007 <http:// money.cnn.com/news/newsfeeds/articles/prnewswire/AQM17916072007-1.htm>