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

professional rich internet applications, ajax and beyond (2007)

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 (16.27 MB, 603 trang )

Professional
Rich Internet Applications:
AJAX and Beyond
Dana Moore
Raymond Budd
Edward Benson
Professional
Rich Internet Applications:
AJAX and Beyond
Professional
Rich Internet Applications:
AJAX and Beyond
Dana Moore
Raymond Budd
Edward Benson
Professional Rich Internet Applications: AJAX and Beyond
Published by
Wiley Publishing, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com
Copyright © 2007 by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 978-0-470-08280-5
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
Library of Congress Cataloging-in-Publication Data is available from the publisher.
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any


means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sec-
tions 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Pub-
lisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222
Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permis-
sion should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis,
IN 46256, (317) 572-3447, fax (317) 572-4355, or online at />LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO
REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF
THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING
WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY
MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND
STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS
SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING
LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS
REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT.
NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HERE-
FROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A
CITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT
THE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR
WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE
AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAP-
PEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.
For general information on our other products and services please contact our Customer Care Department
within the United States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade
dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United
States and other countries, and may not be used without written permission. All other trademarks are the
property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor
mentioned in this book.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not
be available in electronic books.

About the Authors
Dana Moore is a division scientist with BBN Technologies and is an acknowledged expert in the fields
of peer-to-peer and collaborative computing, software agent frameworks, and assistive environments.
Prior to joining BBN, Dana was chief scientist for Roku Technologies, and a Distinguished Member of
Technical Staff at Bell Laboratories. Dana is a popular conference speaker, a university lecturer, and has
published both articles for numerous computing publications, and books, including Peer-to-Peer: Building
Secure, Scalable, and Manageable Networks and Jabber Developer Handbook. Dana holds a master of science
degree in technology management from the University of Maryland, and a bachelor of science in indus-
trial design, also from the University of Maryland.
Raymond Budd is a software engineer with BBN Technologies. He has designed, developed, and sup-
ported a variety of Web applications and other distributed systems in Java, Ruby, and Python. He has
been published in several conference proceedings, such as the Eighteenth National Conference on
Artificial Intelligence, and journals, including Applied Intelligence. Additional areas of interest include
knowledge representations, knowledge engineering, and distributed planning and scheduling.
He received a bachelor of science degree in computer science from the University of Pittsburgh.
Edward (Ted) Benson is a software engineer with BBN Technologies. His experience and interests
include distributed programming frameworks, multi-agent systems, Web development, and knowledge
representation. Ted has developed Web applications for several community groups and companies, and
he has been published in IEEE conference proceedings on the subjects of distributed and multi-agent
systems. He gradated summa cum laude from the University of Virginia with a bachelor of science degree
in computer science.
Credits
Acquisitions Editor
Kit Kemper
Development Editor
Maureen Spears
Technical Editor
William Wright
Production Editor

William A. Barton
Copy Editor
Luann Rouff
Editorial Manager
Mary Beth Wakefield
Production Manager
Tim Tate
Vice President and Executive Group Publisher
Richard Swadley
Vice President and Executive Publisher
Joseph B. Wikert
Graphics and Production Specialists
Brooke Graczyk
Barbara Moore
Heather Ryan
Alicia B. South
Quality Control Technicians
John Greenough
Jessica Kramer
Brian H. Walls
Project Coordinator
Adrienne Martinez
Media Development Project Supervisor
Laura Carpenter Van Winkle
Media Development Specialists
Angie Penny
Kit Malone
Kate Jenkins
Steve Kudirka
Proofreading and Indexing

Aptara
Anniversary Logo Design
Richard Pacifico
Acknowledgments
The authors gratefully acknowledge the contributions of our friend and colleague William Wright,
whom we cajoled into acting as the technical editor and all-around technical conscience of this book.
Our warmest gratitude also to Maureen Spears, our English editor at Wiley, who put up with our terrible
geek humor during conference calls and worked tirelessly to bring the quality of this book up to what
you see before you.
We also appreciate the Web 2.0 luminaries who agreed to share their expertise and candid opinions with
us, and our readers for the interviews scattered throughout the book. These include Dojo Toolkit’s
Alex Russell, Ruby on Rails’ David Heinemeier Hansson, 37Signals’ Jason Fried, and Second Life’s
Wagner James Au. We thank our BBN colleagues John Hebeler, for his entertaining sidebar comments,
and Jonathan Nilsson, for his helpful comments.
Finally, and most important, we thank our friends, families, and significant others for their forbearance.
Writing is a solitary activity that tends to exclude others, even those most important to us; and we appre-
ciate all their support, and promise somehow to make up for the lost time and opportunities.
For Jane, who “walks in beauty, like the night of cloudless climes and
starry skies; And all that’s best of dark and bright meet in her aspect and
her eyes,” and for Caitlin, who, like the spring breeze, breathes new life to
the suffocated hills, and comes as the herald of each new dawn’s
possibilities.
—DM
For Leah, with love. I am inspired by your intelligence, strength, and
beauty, and am immensely grateful for the support and understanding you
gave me as I wrote this. Also for my parents with appreciation for
everything you’ve taught me throughout my life.
—RB
For Grace, her warm eyes, gentle wisdom, and wonderful laugh.

And for my four parents, who taught me all the important things I know in
life.
—EB
Contents
Acknowledgments ix
Introduction xxi
Part I: An Introduction to RIAs 1
Chapter 1: What Characterizes Rich Internet Applications? 3
Rich Internet Applications are “Plastic” 4
An Example of Plastic (Dynamic) Web Pages 4
How Style Sheets Create a Better Page 6
Rich Internet Applications: The Web Is Disruptive (Finally) 8
Rich Internet Applications Are Invisible 9
Invisibility of Google 10
Focusing Your RIAs 11
Rich Internet Applications Break Down Walled Gardens 12
Rich Internet Applications Create New (Unwalled?) Gardens 13
Constraints in the Unwalled Garden 14
Understanding the Counter-Manifesto 15
Rich Internet Applications Are Always Up-to-Date 17
Rich Internet Applications Are OS Killers 19
Web 2.0 Layering 19
Cascading Style Sheets 20
Leaving the Desktop Behind 20
Is Java a Winner or Loser? 20
Rich Internet Applications Are Browser Centric 21
Rich Internet Applications Are Network Centric 21
Rich Internet Applications Are Mind-Altering 23
Observations from a Developer’s Altered Mind 23
Some Observations from Our Altered Minds 23

Rich Internet Applications Are Software as Service 24
Rich Internet Applications Are User Centered 25
Rich Internet Applications Are Inherently Collaborative 25
Rich Internet Applications: Small and Agile Development 26
Rich Internet Applications Are Bound to Change 26
How Do I Change the Way I Develop Applications? 27
How Am I Going to Make Money from RIAs? 28
Rich Internet Applications Are Seductive 29
xii
Contents
Chapter 2: RIA Foundations 35
XML: The Lingua Franca of the Internet 36
Back to the Hip-Bone Song — XML Fundamentals 36
Using Attributes 38
The DOM Tree 39
XHTML: A Language for Documents 42
Document Structure 43
Text Structure 44
Describing Text Type 45
In-text Objects 46
Document Setup 47
CSS: A Language for Style 48
Attaching CSS to a Web Page 50
Painting By Numbers 51
The CSS Cascade Shimmy 53
Taking Full Advantage of CSS in Your RIA 54
JavaScript: A Language for Action 54
Attaching JavaScript to a Web Page 55
Binding JavaScript to User Actions 57
Removing and Adding from the DOM Tree 59

Inspecting and Setting an Element’s Contents 60
A Concluding Example — Angela’s Ristorante 62
Summary 67
Chapter 3: The Programmable Web: The Mashup Ecosystem 69
Getting Ready to Mash 71
The Big Picture 71
XmlHttpRequest Object 72
A Simple First Mashup 73
Working with XML Output 74
Working with JSON Output 86
What’s a Proxy and Why Do I Need One? 92
Working with a Proxy 94
Working without a Proxy 96
XML or JSON 96
The Yahoo and Google Traffic Mashup 97
Getting a Geocode 97
Getting the Traffic Report 102
Dynamically Injecting a SCRIPT Tag into the HEAD 103
Putting Together the Final Mashup 106
Summary 116
xiii
Contents
Chapter 4: Getting Started: Creating Your First RIA 117
Two Scenarios: If Restaurants Were Run Like Web Apps 117
The Unusual Restaurant 118
An Alternative Experience 119
How Does This Relate to My Web App? 120
AJAX versus the Traditional Approach 120
Understanding the Traditional Web Application 121
Limitations of the Traditional Web Application 122

Understanding the Web Application That Uses AJAX 123
Advantages of Using AJAX over the Traditional Approach 125
AJAX Components 125
Development Environment Setup 126
Your First RIA: Hello World 126
Creating HelloWorldv1.html 126
Adding a JavaScript Event Handler 128
Defining the JavaScript Body 128
Creating the Asynchronous Request 128
Defining the Event Handler Function 128
Defining the Callback Function 130
Processing the Server’s Response 131
The Complete HelloWorldv3.html file 132
Creating the helloFiles Directory 133
Adding the Server Side 135
Programming the Server-Side PHP 135
Programming the Java Servlet 138
Enhancing the Client Application 142
Summary 145
Part II: RIAs Explored 147
Chapter 5: Debugging the Client Side 149
Debugging Tools 150
Firefox 150
The Mozilla DOM Inspector 151
The JavaScript Console 152
Venkman 152
FireBug 154
Markup Validation 155
But Wait, There’s More! 156
xiv

Contents
Logging 156
The Alert Function 158
A Very Simple Logger 158
A Homework Assignment 160
Summary 161
Chapter 6: The Model-View-Controller (MVC) Pattern 163
The Model-View-Controller 164
Origins: The Thing-Model-View-Editor 164
The Model-View-Controller Pattern in Detail 165
Using MVC in Java 170
The Model 2 Architecture 171
The Design of Health History in Java 173
MVC Frameworks for Java 174
Web Application Frameworks 176
Ruby on Rails: a Ruby-based MVC Framework 178
TurboGears: A Python-based Alternative to Rails 181
MVC Implementation Quick Reference 184
Summary 184
Chapter 7: JavaScript Library Survey 185
JavaScript Library Basics 186
Why Use JavaScript Libraries? 186
The Various Libraries 188
Library Properties 189
Frequently Provided Library Capabilities 189
JavaScript Libraries in Detail 191
Dojo 191
MochiKit 195
Script.aculo.us 198
Yahoo! UI Library 201

JavaScript Library Quick Reference 203
Summary 204
Chapter 8: Compiling to JavaScript 205
Enter the First Contenders 206
The Google Web Toolkit (GWT) 206
GWT Benefits 207
GWT Drawbacks 208
Developing with GWT 208
xv
Contents
Developer Tools 210
Look and Feel of GWT 212
Automatic Serialization 214
Ruby JavaScript (RJS) 215
RJS Benefits 216
RJS Drawbacks 216
Developing with RJS 217
Look and Feel of RJS 218
Summary 220
Chapter 9: An Introduction to ideaStax 221
ideaStax Concept of Operation 222
Creating a New Stack, Card, or Concept 224
Creating Cards 226
Getting Started: the Essential Elements 230
ideaStax 230
MySQL 231
Ruby on Rails Setup 232
ideaStax: the Implementation Detail 234
Deconstructing Concept, Card, and Stack 234
Verifying Concepts, Cards, and Stacks 235

Implementing the Views 237
Implementing the Controllers 239
Creating Tests for HTTP POST or GET 240
Using the Ruby JavaScript Construct as a Partial Renderer 240
Rails Control Flow 243
Summary 245
Part III: RIA Development in Depth 247
Chapter 10: Form Validation 249
Incorporating Form Validation into Your System 250
Server-Side Validation of the Entire Form 250
Client-Side Validation with JavaScript 251
Asynchronous Server-Side Validation of a Single Form Element 251
Capturing User Information 252
The Unchecked User Form 252
Validation in Practice: Client-Side Validation with Dojo 258
Installing the Dojo Toolkit 258
Getting Started with Dojo 259
xvi
Contents
Using Client-Side Validation Functions 259
Using Dojo Validation Widgets 260
Validation in Practice: Server-Side Validation of the Completed Form 272
Implementing the Server Side 272
Defining the Model 273
Defining the Controller 276
Defining the Helper Class 277
Compiling and Running the Servlet 282
Implementing the Client-Side by Enhancing the View 282
Enhancing the Helper by Adding Validation of the Other Form Fields 284
Validation in Practice: Server-Side Validation of the Username 288

Enhancing the View 289
Enhancing the Controller 291
Summary 293
Chapter 11: Form Usability 295
Overview 296
Approaches to the Usable Form 296
Limitations to Synchronous JavaScript in Forms 296
Advantages to AJAX and JavaScript Effects in Forms 297
Form Usability in Practice: Populating a Field with Server Data 298
Implementing the Server Side 299
Implementing the Client Side by Enhancing the View 305
Form Usability in Practice: Using a Server Backed Combo Box 309
An Auto-Complete Combo Box Example: Car Make 309
A Server-Populated Combo Box Example: Car Model 310
Implementing the Server Side 311
Implementing the Client Side by Enhancing the View 314
Summary 321
Chapter 12: Drag and Drop 325
Introducing Prototype and script.aculo.us 326
Understanding Prototype and script.aculo.us Capabilities 326
Obtaining Prototype and script.aculo.us 327
DOM Elements in the Physical World 327
Draggables 328
Droppables 330
Sortable Lists 332
Drag and Drop in Context: The ideaStax Editor 333
Basic Design 333
Planning for Drag and Drop 335
Implementation Plan 336
xvii

Contents
A Client-Only ideaStax Editor 336
Creating Slides Dynamically with script.aculo.us’ Builder 336
Populating the Library with Draggable Slides 339
Creating a Droppable the Editor Pane 342
Implementing the Sortable Timeline 344
Client-Only Implementation Summary 347
A Server-Backed ideaStax Editor 347
Getting Started with Rails 348
Creating the Model 349
Creating the View 355
Creating the Controller 360
The End-to-End ideaStax Editor 364
Summary 365
Chapter 13: User Interaction, Effects, and Animation 367
Effects Introduction: Hide and Seek 368
The script.aculo.us Effect Class 369
Using Effects 370
Example: Effects-Based Notifications 372
Binding Effects to Other script.aculo.us Actions 374
Combining Effects 377
Modal Windows and the ideaStax Previewer 377
Positioning the Preview Window 379
Fetching the Preview Window 381
Transitioning In and Out of the Preview Window 383
Making the Preview Modal 384
A Completed Modal Preview 386
Summary 387
Chapter 14: Tagging and Rating (I): Creating an Infrastructure 389
Understanding the Tagging Problem 390

A Tagging Application 391
Getting Started: the Essential Elements 395
Python 396
MySQL 396
MySQLdb 396
Flickr Photo API 397
Apache Web Server 397
MochiKit 398
Data Mining 400
Downloading Photo Metadata 400
Accessing Photo Metadata 401
xviii
Contents
Setting Up the Data Model 403
Setting Up the Data Tables 404
Populating the Pictures Data Base 408
Setting Up the Flickr Photo Interface 411
Scoring Tags 415
Using Styles to Implement the Tag Cloud 415
JSON Data from the Tagger 417
Database Lookups 418
Server-Side CGI for Getting a Tagged Photo 420
The Dynamically Generated RIAPage 422
Summary 422
Chapter 15: Tagging and Rating (II): Using Social Capability 423
Stax So Far 423
Stax Design Center 424
Retrieving Concepts and Cards 426
Getting Started: the Essential Elements 427
Implementing the Controllers and Views 437

Summary 448
Part IV: Advanced Selected Topics 451
Chapter 16: Providing an API 453
Choosing How to Expose Your Service 454
The Home-Grown Solution 454
The Web Service Solution 454
Choosing Casual over Formal 455
Exposing a Service over HTTP 455
Metering Access 455
Defining the Interface 458
An Example API for Stax 459
Writing Documentation 459
Documentation Sample 459
Constructing the API 462
Summary 465
xix
Contents
Chapter 17: RIA Widgets 467
Surveying the Field 468
Getting Started: the Essential Elements 468
Unpacking a Widget with the Widget Converter 469
File Structure and Packaging 470
Widget Specification File Overview 471
Defining Your First Widget: a Hello World Exercise 472
The Basic Hello World 472
Packing the Widget with the Widget Converter 474
Extending Hello World 475
A More Useful Example: Incorporating the Stax API 482
Setting Up the Example 483
Creating the Basic Widget 483

Adding File Drag and Drop 486
Uploading the Concept to the Stax Server 488
Adding User Preferences 490
Summary 495
Chapter 18: Rich Immersive Environments 497
Looking Back in Rich Immersion: The World of Magic Cap 498
Forward in Time: The World of Snow Crash 500
And Now: The World of Second Life 500
Second Life: The Programmer’s View 502
Getting Started: The Essential Second Life Elements 510
Connecting Second Life to Real Life 511
A Web 2.0 Demonstration of Second Life 515
Summary 518
Part V: Appendix 523
Appendix: Dojo Validation Functions and Flags 525
Basic Dojo Validation Functions and Flags 525
Dojo Internet Validation Functions and Flags 529
Locale-Specific Validation Functions in Dojo 531
Index 533
Introduction
And now for something completely different.
—Monty Python Tagline
This introduction orients you to the rest of the book and takes you for a brief tour of its primary subject,
Rich Internet Application (RIA) architecture and how it evolved. In looking at how we could best serve
our readers, we tried to create a blend of three elements to accomplish the following:
❑ Give you a sense of how RIAs are different from the previous generation of Web applications
and how this difference is important to you, whether you are a corporate or independent soft-
ware developer
❑ Present significant supporting code examples, rich enough to be complete and nontrivial, but

simple enough to present in a page or two of code
❑ Describe and demonstrate important frameworks and APIs
Who Is This Book For?
The authors make no assumptions about the background of the book’s readers other than that you are
working software developers interested in practical solutions to real-world problems. This book explains
how to use enabling technologies to create new kinds of distributed systems with features rivaling desk-
top systems. Whether your skills are in Web development, server architectures, or agile languages, you
should find value in this book.
Given the fact that the examples are written in Python, Java, and Ruby on Rails, it is best if you have
some familiarity with one of these languages. We do assume you have some experience developing and
deploying Web applications, and can read basic UML diagrams. Finally, you should be familiar with
basic database management operations, although any required database administration steps are clearly
outlined in each chapter.
What Is This Book’s Focus?
Because the authors are professional corporate software developers, we know that the quickest road to
understanding code and APIs is to review working code examples, but often books consist of a stream of
didactic examples. Although this approach may reveal important points of a topic, it ultimately leaves
xxii
Introduction
you unfulfilled because the simple examples don’t build anything compelling outside of the context of
the point the author is trying to make. Thus, this book focuses on an interesting and feature-complete
application that functions as a recurring theme holding the book together and helps you to gain a grow-
ing sense of mastery over RIA design, frameworks, and implementation.
Accordingly, you have the opportunity to build a capstone application, which we call ideaStax. IdeaStax is
an idea capture tool that enables users, either singly or in community, to record, tag, search, organize, and
present ideas. Ideas are the atomic units of ideaCards, and ideaCards are the building blocks of ideaStax.
IdeaStax serves multiple other purposes too. For one thing, it serves to illustrate the notion of how appli-
cations might change in capability and character if they were built from the ground up to reflect RIA con-
cepts and capabilities. In a sense, you might think of ideaStax as a re-envisioning of what a desktop
application such as Microsoft’s PowerPoint might be like if it had been designed to conform to the con-

cepts of RIAs in the twenty-first century, instead of the rich client platform (RCP) of the twentieth.
In addition to getting the code for ideaStax from the Wrox publishing site (
www.wrox.com), the authors
are developing a site (
ideaStax.com) where you can also contribute ideas and code, show off your
skills, and participate in evolving the application and its capabilities in the best tradition of open-source
software. If your contributions are worthwhile, you can become a committer to the project.
The Book’s Topical Approach
For several decades now, developers have believed certain things to be objectively true, perhaps even
indisputable. We consider ourselves members of a specific development and deployment “tribe.” Rather
than consider yourself a developer, you may consider yourself to be a “Java developer,” or “Microsoft
.Net developers,” with the limitations and technology constraints implied by membership in the tribe.
In the case of Java, this means “one language, many platforms,” and in the case of Microsoft Windows 32
APIs, it means “a few languages, one platform.” In any event, writing for a rich client platform tradition-
ally means having developers make compromises, having end users manage installation and updates,
and having the involvement of corporate IT departments. The economics and mechanics of selling and
buying licensed software have created a heavy burden for everyone involved in the process.
It’s hardly possible to have been a software developer for any length of time and not have written code
using a rich client API for Windows, MAC OS/X, or Linux. Thus, we’re all familiar with the rich client
platform (RCP) model. Almost every application we’ve written, used, managed, or deployed over the
last three decades on microcomputers adheres to RCP capabilities and limitations. When you think like
an RCP developer, you may take for granted that the operating system, data access and storage, and the
user’s experience of the application are tightly bound. This accounts for the responsiveness of certain
types of applications — word processors, for example.
Now this status quo is changing, and changing rapidly. By the end of 2005, a good deal of “buzz” was
emerging over something called AJAX (asynchronous JavaScript and XML). AJAX, while simply an
umbrella term for assembling applications by using several mature technologies already in common use,
nevertheless seemed to evoke something more than the sum of its constituent parts. There’s now grow-
ing recognition that a tectonic shift promises to change the very foundations of how we develop and
deploy applications. The Web is undergoing a profound transformation from a collection of news arti-

cles, static forms, and bulletin boards to a location-agnostic computing platform in and of itself.

×