利用Java技术实践Ajax 项目


this print for content only—size & color not accurate spine = 0.998" 528 page count EMPOWERING JAVA™ DEVELOPERS WITH AJAX TECHNIQUES Practical Ajax Projects with Java™ Technology Dear Reader, We all know that Ajax is a hot topic right now, and I’m sure you’ve noticed just how many books are now available on the subject. Why would I write another, you ask? Simply put, it is one thing to read a tutorial book on a topic, but many programmers learn best by picking apart actual working applications. And that’s what this book is all about! Within it you will find a brief refresher of key Ajax concepts and development environment setup, but that’s not the focus. The main bulk of this book consists of seven complete, real-world Ajax applications, built with Java™ technologies, including: • AjaxReader—The prototypical Ajax application: an RSS aggregator • PhotoShare—A photo-sharing application that includes some cool animation effects and graphical embellishments • AjaxChat—A multiuser chat application built on the ubiquitous Struts framework • AJAX Warrior—A full web-based adventure game utilizing Ajax ...and many more! You will learn by doing—by seeing how all the pieces fit together to form the whole. By the time you finish this book, you will be well versed in all things Ajax, and quite a bit more, including JavaScript™, CSS, DOM scripting, JSON, XML, Jakarta Commons components, Apache Struts, OpenSymphony WebWork, HSQLDB, and even basic game design theory! I truly believe that if you are a programmer who learns best by looking at code, this book will serve you very well indeed. See you inside! Frank W. Zammetti SJCP, MCSD, MCP, CNA, CIW Associate, etc. US $49.99 Shelve in Java™ Programming User level: Intermediate–Advanced Zammetti THE EXPERT’S VOICE® IN WEB DEVELOPMENT Frank W. Zammetti Practical Ajax Projects with Java™ Technology CYAN MAGENTA YELLOW BLACK PANTONE 123 CV ISBN 1-59059-695-1 9 781590 596951 54999 6 89253 59695 1 Companion eBook Available Accelerate your learning with professional Ajax projects, powered by Java™ technologies! Supports all current Java™ versions, including 5 and 6! Supports all current Java™ versions, including 5 and 6! www.apress.com SOURCE CODE ONLINE Companion eBook See last page for details on $10 eBook version forums.apress.com FOR PROFESSIONALS BY PROFESSIONALS™ Join online discussions: THE APRESS ROADMAP Foundations of Ajax Pro JavaScript™ Techniques Ajax Patterns and Best Practices Beginning POJOs: From Novice to Professional Beginning CSS Web Development: From Novice to Professional Beginning JavaScript™ with DOM Scripting and Ajax: From Novice to Professional Practical Ajax Projects with Java™ Technology Pro Ajax and Java™ Frameworks Ajax Projects with Java ™ Technology Practical Frank W. Zammetti Practical Ajax Projects with JavaTM Technology 6951FM 7/7/06 8:23 AM Page i Practical Ajax Projects with JavaTM Technology Copyright © 2006 by Frank W. Zammetti All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher. ISBN-13 (pbk): 987-1-59059-695-1 ISBN-10 (pbk): 1-59059-695-1 Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1 Trademarked names may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, we use the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S. and other countries. Apress, Inc. is not affiliated with Sun Microsystems, Inc., and this book was written without endorsement from Sun Microsystems, Inc. Lead Editor: Chris Mills Technical Reviewer: Herman van Rosmalen Editorial Board: Steve Anglin, Ewan Buckingham, Gary Cornell, Jason Gilmore, Jonathan Gennick, Jonathan Hassell, James Huddleston, Chris Mills, Matthew Moodie, Dominic Shakeshaft, Jim Sumser, Keir Thomas, Matt Wade Project Manager: Richard Dal Porto Copy Edit Manager: Nicole LeClerc Copy Editor: Liz Welch Assistant Production Director: Kari Brooks-Copony Production Editor: Kelly Gunther Compositor: Lynn L’Heureux Proofreader: Linda Seifert Indexer: Brenda Miller Cover Designer: Kurt Krames Manufacturing Director: Tom Debolski Distributed to the book trade worldwide by Springer-Verlag New York, Inc., 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax 201-348-4505, e-mail orders-ny@springer-sbm.com, or visit http://www.springeronline.com. For information on translations, please contact Apress directly at 2560 Ninth Street, Suite 219, Berkeley, CA 94710. Phone 510-549-5930, fax 510-549-5939, e-mail info@apress.com, or visit http://www.apress.com. The information in this book is distributed on an “as is” basis, without warranty. Although every precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in this work. The source code for this book is available to readers at http://www.apress.com in the Source Code section. 6951FM 7/7/06 8:23 AM Page ii For my wife Traci, who probably does not understand a single thing in this book, but who reminded me why I love her by being more excited for me than I was for myself about my first book. For my two children, Andrew and Ashley, for whom I gladly worked all those long hours. Thanks for leaving Daddy alone (usually) long enough to get this done; I owe you each a pony. (I hope you both know about sarcasm by the time you read this!) For Mom and Dad, who started it all with the seemingly innocuous purchase of a Timex Sinclair 1000 computer for Christmas 1982 (or 1983—my memory’s a bit flaky 20+ years later!). For John J. Sheridan, for keeping the Shadows off our backs. 6951FM 7/7/06 8:23 AM Page iii 6951FM 7/7/06 8:23 AM Page iv Contents at a Glance About the Author . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi About the Technical Reviewer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii About the Illustrator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvi Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii PART 1 ■ ■ ■ Programming Using Ajax and Java ■CHAPTER 1 Ajax: The Brave New World . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 ■CHAPTER 2 The Pillars of Ajax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 ■CHAPTER 3 The Server Side of the Equation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 PART 2 ■ ■ ■ The Projects ■CHAPTER 4 Karnak: Type-Ahead Suggestions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 ■CHAPTER 5 InstaMail: An Ajax-Based Webmail Client . . . . . . . . . . . . . . . . . . . . . . 143 ■CHAPTER 6 AjaxReader: Because Every Ajax Book Has to Have One! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203 ■CHAPTER 7 PhotoShare: Share Your Visual Life with Your Friends . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253 ■CHAPTER 8 The Organizer: Get Yourself Organized Now! . . . . . . . . . . . . . . . . . . 313 ■CHAPTER 9 AjaxChat: Chatting, the Ajax Way! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353 ■CHAPTER 10 AJAX Warrior: Back to the Future in a Fun Way! . . . . . . . . . . . . . . . 407 ■APPENDIX A The XMLHttpRequest Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479 ■APPENDIX B Libraries, Websites, and Books, Oh My! . . . . . . . . . . . . . . . . . . . . . . . 483 ■INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489 v 6951FM 7/7/06 8:23 AM Page v 6951FM 7/7/06 8:23 AM Page vi Contents About the Author . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi About the Technical Reviewer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii About the Illustrator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvi Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii PART 1 ■ ■ ■ Programming Using Ajax and Java ■CHAPTER 1 Ajax: The Brave New World . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 A Brief History of Web Development: The “Classic” Model . . . . . . . . . . . . . 3 What Is “Wrong” with the Classic Web? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Enter Ajax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 Why Is Ajax a Paradigm Shift? On the Road to RIAs . . . . . . . . . . . . . . . . . . 16 Let’s Get to It: Our First Ajax Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 Choices in Ajax Toolkits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 Alternatives to Ajax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 ■CHAPTER 2 The Pillars of Ajax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 JavaScript Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 Object-Oriented JavaScript, or Making JavaScript “Non-Kiddie-Like” . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 The Document Object Model and Scripting: Manipulating Content on the Fly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 XML: The Language of Languages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 Parsing XML in JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 Cascading Stylesheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 vii 6951FM 7/7/06 8:23 AM Page vii ■CHAPTER 3 The Server Side of the Equation . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 The Project Development Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 Ant: Building Java Applications the Open Source Way . . . . . . . . . . . . . . . . 84 Apache Tomcat: Something for Nothing! . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 Webapps, Servlets, JSPs, and Parsing XML on the Server . . . . . . . . . . . . 96 Installing and Playing with the Applications . . . . . . . . . . . . . . . . . . . . . . . . 111 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 PART 2 ■ ■ ■ The Projects ■CHAPTER 4 Karnak: Type-Ahead Suggestions . . . . . . . . . . . . . . . . . . . . . . . . 115 Requirements and Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 How We Will Pull It Off . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 Visualizing the Finish Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 Dissecting the Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 Suggested Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142 ■CHAPTER 5 InstaMail: An Ajax-Based Webmail Client . . . . . . . . . . . . . . . 143 Requirements and Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 How We Will Pull It Off . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144 Visualizing the Finish Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147 Dissecting the Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152 Suggested Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201 ■CHAPTER 6 AjaxReader: Because Every Ajax Book Has to Have One! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203 Requirements and Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203 How We Will Pull It Off . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204 Visualizing the Finish Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206 Dissecting the Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210 Suggested Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251 ■CONTENTSviii 6951FM 7/7/06 8:23 AM Page viii ■CHAPTER 7 PhotoShare: Share Your Visual Life with Your Friends . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253 Requirements and Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253 How We Will Pull It Off . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254 Visualizing the Finish Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258 Dissecting the Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262 Suggested Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312 ■CHAPTER 8 The Organizer: Get Yourself Organized Now! . . . . . . . . . . . . 313 Requirements and Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313 How We Will Pull It Off . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314 Visualizing the Finish Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321 Dissecting the Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324 Suggested Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352 ■CHAPTER 9 AjaxChat: Chatting, the Ajax Way! . . . . . . . . . . . . . . . . . . . . . . . 353 Requirements and Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353 How We Will Pull It Off . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354 Visualizing the Finish Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365 Dissecting the Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367 Suggested Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406 ■CHAPTER 10 AJAX Warrior: Back to the Future in a Fun Way! . . . . . . . . 407 Requirements and Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407 How We Will Pull It Off . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408 Visualizing the Finish Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413 Dissecting the Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417 Suggested Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 476 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 477 ■CONTENTS ix 6951FM 7/7/06 8:23 AM Page ix ■APPENDIX A The XMLHttpRequest Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479 What Is the XMLHttpRequest Object? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479 What Browsers Support the XMLHttpRequest Object? . . . . . . . . . . . . . . 479 Is the XMLHttpRequest Object a W3C Standard? (Or Any Other Kind of Standard for That Matter!) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 480 How Do I Use the XMLHttpRequest Object? . . . . . . . . . . . . . . . . . . . . . . . 480 XMLHttpRequest Object Method and Properties Reference . . . . . . . . . . 481 XMLHttpRequest Object Status Codes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482 ■APPENDIX B Libraries, Websites, and Books, Oh My! . . . . . . . . . . . . . . . . . 483 Libraries/Toolkits/Products . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483 Websites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485 Books . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 486 ■INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489 ■CONTENTSx 6951FM 7/7/06 8:23 AM Page x About the Author ■FRANK W. ZAMMETTI is a web architecture specialist for a leading worldwide financial company by day, and a PocketPC and open source developer by night. He is the founder and chief soft- ware architect of Omnytex Technologies, a PocketPC development house. He has more than 12 years of “professional” experience in the IT field, and 12 more of “amateur” experience. He began his nearly lifelong love of computers at age 7 when he became one of four students chosen to take part in the school district’s pilot computer program. A year later, he was the only participant left! The first computer Frank owned (around 1982) was a Timex Sinclair 1000, on which he wrote a program to look up movie times for all of Long Island (and without the 16k expansion module!). After that, he moved on to an Atari computer, and then a Commodore 64, where he spent about 4 years doing nothing but assembly programming (games mostly). He finally got his first IBM-compatible PC in 1987, and began learning the finer points of programming (as they existed at that time!). Frank has primarily developed web-based applications for about 8 years. Before that, he developed Windows-based client-server applications in a variety of languages. Frank holds numerous certifications, including SCJP, MCSD, CNA, i-Net+, A+, CIW Associate, MCP, and numerous BrainBench certifications. He is a contributor to a number of open source projects, including DataVision, Struts, PocketFrog, and Jakarta Commons. In addition, Frank has started two projects: Java Web Parts and The Struts Web Services Enablement Project. He also was one of the founding members of a project that created the first fully functioning Commodore 64 emulator for PocketPC devices (PocketHobbit). Frank has authored various articles on topics that range from integrating DataVision into web apps to using Ajax in Struts-based applications. He is currently working on a new applica- tion framework specifically geared to creating next-generation web applications. xi 6951FM 7/7/06 8:23 AM Page xi 6951FM 7/7/06 8:23 AM Page xii xiii About the Technical Reviewer ■HERMAN VAN ROSMALEN works as a developer/software architect for De Nederlandsche Bank N.V., the central bank of the Netherlands. He has more than 20 years of experience in develop- ing software applications in a variety of programming languages. Herman has been involved in building mainframe, PC, and client-server applications. The past 6 years, however, he has been involved mainly in building J2EE web-based applications. After working with Struts for years (pre-1.0), he got interested in Ajax and joined the Java Web Parts open source project in 2005. Herman lives in a small town, Pijnacker, in the Netherlands with his wife Liesbeth and their children, Barbara, Leonie, and Ramon. 6951FM 7/7/06 8:23 AM Page xiii 6951FM 7/7/06 8:23 AM Page xiv xv About the Illustrator ■ANTHONY VOLPE did the illustrations for this book and the AJAX Warrior video game. He has worked on several video games with author Frank Zammetti, including Invasion Trivia, Io Lander, and Krelmac, and Gentoo Arcade. Anthony lives in Collegeville, PA, and works as a graphic designer and front-end web developer. His hobbies include recording music, writing fiction, making video games, and going to karaoke bars to make a spectacle of himself. 6951FM 7/7/06 8:23 AM Page xv xvi Acknowledgments Many people helped make this book a reality in one form or another, and some of them may not even realize it! I’ll try and remember them all here, but chances are I haven’t, and I apologize in advance! First and foremost, I would like to thank everyone at Apress Publishing who made this book a reality, and for taking a chance on an essentially unknown quantity. I have nothing but kind words to say about everyone I interacted with and the whole process in general. Thank you for making it such a smooth, rewarding ride! I would like to especially thank my editor, Chris Mills, and my project manager, Richard Dal Porto. Both of you guided me through an entirely unfamiliar territory and made it a pleas- ure, and I can’t thank either of you enough for it! I know you were both just doing your jobs, and that makes it all that much more impressive. And besides, I turned Chris on to Shadow Gallery, so in a sense he owes me a big thanks! A great deal of thanks goes to Herman van Rosmalen, one of my partners in crime on the Java Web Parts (http://javawebparts.sourceforge.net) project, and technical reviewer for this book. I know you put in a lot of time and effort in keeping me honest, and I can’t tell you how much I appreciate it! Even when we perhaps didn’t agree on things, you always made me think and consider alternatives, and that makes you truly worth your weight in gold. Now let’s get to some of the items on the JWP to-do list! A big thanks must also go to Anthony Volpe, the fine artist who did the illustrations for this book. He and I have been friends for about 10 years now, and we have collaborated on a number of projects, including three PocketPC games (check ’em out: www.omnytex.com) as well as a couple of Flash games (www.planetvolpe.com/crackhead) and some web cartoons (www.planetvolpe.com/du). He is a fantastic artist and, as I’m sure you can see for yourself, an incredibly creative person—and a good friend to boot. I would like to thank Wendy Smoak, who put up with many rants from me during the course of writing this book. Believe it or not, you even helped solve a technical problem or two along the way, which certainly is very much appreciated, but having the ear there to yell into when the going got tough was even more appreciated! I would also like to thank those who built some of the libraries used in this book, includ- ing Joe Walker (DWR), all the folks working on Dojo, and Sam Stephenson (Prototype). Last but most definitely not least, I would like to thank everyone who buys this book! I sincerely hope you have as much fun reading it as I did writing it, and I hope that you find it to be worth your hard-earned dollars and that it proves to be an educational and eye-opening experience. As I said, I know I am almost certainly forgetting a boatload of people, so how about I just thank the entire world and be done with it? In fact, if I had the technology, I’d be like Wowbag- ger the Infinitely Prolonged, only with “Thanks!” instead of insults. And on that note, let’s get to some code! 6951FM 7/7/06 8:23 AM Page xvi xvii Introduction Who would have imagined that someone cleverly applying the name of a popular cleaning agent to a programming technique would change the world? That’s exactly what is happening right now! Ajax, Asynchronous JavaScript and XML, has taken the web development world by storm, and for good reason. It not only ushers in a new era of potential for web applications to “grow up,” so to speak, in terms of the user interface they provide their human users, but also allows for a fundamental paradigm shift in the way people approach web development. No longer are we bound to the document/page model of things, but the world of user-driven events, in a much more real way than was possible before, can now become a reality. Web applications can now be developed, perhaps for the first time—at least the first time in terms of developer mindshare (because, as you will learn, Ajax is not really anything new!). Cool! Ajax has enjoyed a somewhat extended “hype bubble,” as I like to call it. Usually, things like this come and go in the blink of an eye in Internet time. But we’re going on over a year now since that fateful day when someone smarter than the rest of us, at least in terms of nifty naming, came up with a name that described something many of us had been doing for a long time. You know what they say: it’s not so much the idea that matters, it’s who names it first that does. The fact that the hype is still going strong shows that Ajax may in fact be something differ- ent. And really, it isn’t so much hype any more as it is people coming to grips with the reality of it, wanting to get past the marketing and the initial “wow” factor, and realizing that there is a lot of good there to be harnessed. Maybe it isn’t just a pretty name—maybe there is some meat there. Indeed, there is! A big part of the reason I wrote this book is because in order for many of us programmers to see why Ajax may be more than a temporary fad and much more of a paradigm shift, we have to see it in action. We can read all the white papers we want, we can ingest all the intro- ductory articles on it that we can find, and we still will be scratching our heads and saying, “OK, I understand the mechanics of it, but how can it be applied in the real world?” My goal with this book is to give programmers real demonstrations of how Ajax can be used in real applications in cool ways, and explain how Ajax can reduce our dependency on fossil fuels and result in world peace. OK, you got me. It can’t replace gasoline—yet. Gimme another week. Seriously though, this book is for the programmers out there who learn better when they are seeing real code in action, code they can dissect and play with. It isn’t written for the theorists among us, or those who no longer twiddle bits on a regular basis. That isn’t to say architects, of which I am one (I am just fortunate enough to still be able to write code too!), can’t get anything from this book. Of course they can! But those in the trenches making the glorious designs a real- ity are the ones who will benefit most, I believe. So, why should you read this book? Well, for starters, there’s a game in it! And I’m not talk- ing a hidden Easter egg game… flip to Chapter 10 right now… go ahead, I’ll wait. See? I wasn’t kidding! 6951FM 7/7/06 8:23 AM Page xvii Aside from that, six other projects await you, each different from the others, and each showcasing how Ajax can make web development better, richer, and ultimately more dynamic. You will be introduced to a number of approaches, a number of different libraries, so that as you move forward in your own Ajax work you will be able to decide what approach suits you and the situation best, and you will have ready examples to get you started. On a personal note, I have to say that I had a great deal of fun writing this book. It was my first, so it really could have been a bad experience, but it simply was the exact opposite. Sure, it was quite a lot of hard work, and I can tell you that my sleep habits have been pretty seriously messed up over the course of writing it! But it was well worth it. I truly believe that any devel- oper who reads this book and explores the applications described within will gain a great deal of knowledge and experience, and I think have a good time doing it too. If you have a good time reading it and learn something in the process, then my mission has been accomplished. An Overview of This Book Chapter 1 is an introduction to the progression of web development in general and to Ajax in particular. Chapter 2 covers the basics required to make sense of all this Ajax stuff: JavaScript, CSS, DOM scripting, and XML are all touched upon at an introductory level. Chapter 3 talks about the server side of things, including a brief introduction to Ant, Apache Tomcat, webapps, servlets, JSPs, and a little more on XML. Chapter 4 begins the projects, starting with Karnak, a concept very roughly, slightly, sort of, maybe, borrowed from Google Suggest. This chapter introduces AjaxTags in Java Web Parts (don’t worry if you don’t know what this, or anything else mentioned here, is… we’ll get to that!). Chapter 5 is a webmail client, similar to Google’s Gmail. With this project you will be introduced to a cool Ajax library named DWR. Chapter 6 presents a fairly typical Ajax application: an RSS feed reader. This project again demonstrates the usage of AjaxTags in Java Web Parts. Chapter 7 is an application named PhotoShare, which allows you to build collections of photographs and share them with your friends and family. This application demonstrates some nifty animation techniques, and introduces another library: Dojo. Chapter 8 is a project called The Organizer, which is intended to be a basic PIM applica- tion (i.e., notes, tasks, appointments, and contacts). With this project you will learn about a popular application framework named WebWork, as well as Spring a little bit, and Prototype, one of the most popular Ajax libraries. Chapter 9 is an Ajax-based chat application named, unimaginatively, AjaxChat. This application is built on what may be the most famous framework of them all, Struts, and uses “naked” Ajax, that is, no library at all. Chapter 10, finally, is the game! AJAX Warrior is its name, and it too is built using “naked” Ajax, and introduces a popular data format frequently seen in Ajax applications called JSON. ■INTRODUCTIONxviii 6951FM 7/7/06 8:23 AM Page xviii ■INTRODUCTION xix Obtaining This Book’s Source Code All the examples in this book are freely available from the Source Code section of the Apress website. In fact, due to the nature of this book, you will absolutely have to download the source before you begin Chapter 4. To do so, visit www.apress.com, click the Source Code link, and find Practical Ajax Projects with JavaTM Technology in the list. From this book’s home page you can download the source code as a zip file. The source code is organized by chapter. Obtaining Updates for This Book Writing a book is a big endeavor, quite a bit bigger than I thought it would be initially! Contrary to what I claim in private to my friends, I am not perfect. I make mistakes like everyone else. Not in this book, of course. Oh no, none at all. AHEM. Let me apologize in advance for any errors you may find in this book. Rest assured that everyone involved has gone to extremes to ensure there are none—but let’s be real here, we’ve all read technical books before, and we know that the cold, sharp teeth of reality bite every now and again. I’m sorry, I’m sorry, I’m sorry! A current errata list is available from this book’s home page on the Apress website (www.apress.com), along with information about how to notify us of any errors you may find. This will usually involve some sort of telepathy, but we hear Windows Vista is being pushed back a few months so that feature can be added. Contacting the Author I very much would like to hear your questions and comments regarding this book’s content and source code examples. Please feel free to e-mail me directly at fzammetti@omnytex.com (spammers will be hunted down by Sentinels and disposed of). I will reply to your inquiries as soon as I can, but please remember, I do have a life (ha, ha! I’m funny!), so I may not be able to reply immediately. 6951FM 7/7/06 8:23 AM Page xix 6951FM 7/7/06 8:23 AM Page xx Programming Using Ajax and Java I never think of the future—it comes soon enough. —Albert Einstein We’ve heard that a million monkeys at a million keyboards could produce the complete works of Shakespeare; now, thanks to the Internet, we know that is not true. —Robert Wilensky The computing field is always in need of new clichés. —Alan Perlis The ’Net is a waste of time, and that’s exactly what’s right about it. —William Gibson The most overlooked advantage to owning a computer is that if they foul up there’s no law against whacking them around a little. —Joe Martin The most likely way for the world to be destroyed, most experts agree, is by accident. That’s where we come in; we’re computer professionals. We cause accidents. —Nathaniel Borenstein PART 1 ■ ■ ■ 6951ch01 7/7/06 8:11 AM Page 1 6951ch01 7/7/06 8:11 AM Page 2 Ajax: The Brave New World If this is your first experience with Ajax, and even web development in general, this chapter will serve as a good introduction to get you up to speed for what is to come. If, however, you are a relatively experienced developer, and especially if Ajax is not new to you, feel free to skip this chapter, as it will likely be just a review for you. This chapter begins our exploration of Ajax by examining how applications in general, and web applications in particular, have been developed over the past decade and a half or so. You’ll discover an interesting cycle in terms of the basic structure of appli-cations. We’ll look at some great examples of Ajax in action and talk about why Ajax is important and how it can fundamentally alter how you develop applica- tions. You’ll encounter your first code sample demonstrating Ajax in a very simple, basic way. We’ll also briefly touch on some of the alternatives to Ajax, and some of the existing libraries and toolkits that make Ajax easier. A Brief History of Web Development: The “Classic” Model In the beginning, there was the Web. And it was good. All manner of catchy new words, phrases, and terms entered the lexicon, and we felt all the more cooler saying them (come on, admit it, you felt like Spock the first couple of times you used the word “hypertext” in conver- sation, didn’t you?). “Webapps,” as our work came to be known, were born. These apps were in a sense a throwback to years gone by when applications were hosted on “big iron” and were accessed in a timeshare fashion. They were in no way, shape, or form as “flashy” as the Visual Basic, PowerBuilder, and C++ “fat clients” that followed them (which are still used today, although less so with the advent of webapps.) But those fat clients did, and still do in many cases, get the job done, just like those timeshare systems of old. In fact, if you really think about it, application development has followed a very up-and- down pattern, and if you walk down the timeline carefully and examine it, this pattern begins to emerge. Starting with what I term the “modern” era, that is, the era in which applications took a form that most of us would basically recognize, we first encounter simple terminal emulation devices (for the sake of this argument, we’ll skip the actual terminal period!) used to access remotely running processes. Screens like the one shown in Figure 1-1 were typical of those types of applications. 3 CHAPTER 1 ■ ■ ■ 6951ch01 7/7/06 8:11 AM Page 3 Figure 1-1. TN3270 mainframe “green-screen” terminal display TN3270 screens are, of course, completely relevant in the sense that they are still used quite a bit, especially in the business world, as anyone who has done any sort of mainframe work can attest to. There are two interesting things to note, for the sake of this discussion. First, notice the simple nature of the user interfaces (UIs) back then—they were text-only, usually limited to 80 columns by 25 lines of text, with extremely limited data entry capabili- ties—essentially just editable mapped regions. Things like dropdowns, checkboxes, and grids were completely unknown in this domain. If it was a well-written application, you would be fortunate and have a real menu like so: C. Create Record D. Delete Record E. Edit record If you were unlucky, you would just have something like this: ….. 01A7C0D9ABABAC00 ….. 89A6B3E34D79E998 If you have never worked on a mainframe, let me briefly explain what that is. For editing files (called data sets) on a mainframe, you usually use a tool called TSO/ISPF. This is just a form of text editor. This editor can be flipped between textual display and hex display, and the above is the hex display version. The dots that precede each line make up the command area. For instance, to insert a line above the line that begins with 89, you would go to the first dot in CHAPTER 1 ■ AJAX: THE BRAVE NEW WORLD4 6951ch01 7/7/06 8:11 AM Page 4 that line and replace it with i, then press the Enter key. If you wanted to delete that line, plus the line that starts with 01, you would go to the line that starts with 01, type dd over the first two dots, then go to the line you just inserted and put dd there as well, then press Enter (dd is for deleting a block of lines, you can use a single d to delete a single line). Second, and more important here, is the question of what happens when the user per- forms an action that requires the application to do something. In many cases, what would happen is that the mainframe would redraw the entire screen, even the parts that would not change as a result of the operation. Every single operation occurred on the mainframe, and there was no local processing to speak of. Not even simple input validation was performed on the client; it was simply a view of a remote application’s state, nothing more. With the advent of the PC, when the amount of local processing power advanced orders of magnitude, a new trend emerged. At this point we began to see applications hosted locally instead of on central mainframes where at least some portion of the application actually exe- cuted locally. Many times, the entire application itself was running on the machine that the user was using. With the growth in popularity of Microsoft Windows more than anything else, “fat clients,” as they came to be known, were suddenly the de facto standard in application development. The UI available in this paradigm was immensely more powerful and user- friendly, but the central hardware faded in importance for the most part (things like database servers notwithstanding). Screens like the one in Figure 1-2 became the norm. Figure 1-2. A typical “fat-client” application Note how much richer the available UI metaphors are. It should come as no surprise to you and the rest of the user community out there that this is universally seen as “better” (you do see this as better, don’t you?). Better is, of course, a relative term, and in some cases it is not CHAPTER 1 ■ AJAX: THE BRAVE NEW WORLD 5 6951ch01 7/7/06 8:11 AM Page 5 better. You would think that people doing heads-down data entry all day might actually prefer those old green screens more because they lend themselves to more efficient keyboard-based data entry efficiency. No fussing with a mouse. No pointing and clicking. No need to take their eyes off the document they are keying off of to save a record. While all of that is true, it cannot be denied that, by and large, people will choose a fat-client version of a given application over a text-only version of it any day of the week! Go ahead, I dare you! Take an existing mainframe application and put it side by side with a fat-client version of the same application and see how many users actually want the mainframe version. I’ll give you a hint: it will be less than 1, but not negative. Thinking about how the application actually functions, though, what happens here when the user clicks a button, for example, or slides a slider, or clicks on a menu item? In most cases, only some region of the screen will be updated, and no external system is interacted with (usually). This is obviously more efficient and in all likelihood more user-friendly as well. But what happened next in our timeline? A bit of a monkey wrench got thrown in the works with the rise of the Internet, and more specifically, the World Wide Web component, or just the Web for short (remember, the Web is not, in and of itself, the Internet!). With the emergence of the Web, screens like the one in Figure 1-3 became commonplace. Figure 1-3. omnytex.com as seen in Lynx, a text-based browser Wait a second, what happened? Where did all our fancy radio buttons, 3D buttons, list boxes, and all that go? The first iteration of the Web looked a heck of a lot, visually, like the old mainframe world. More important, though, is what was happening under the hood: we went CHAPTER 1 ■ AJAX: THE BRAVE NEW WORLD6 6951ch01 7/7/06 8:11 AM Page 6 back to the old way of doing things in terms of centralized machines actually running the applications, and entire screens at a time being redrawn for virtually every user interaction. In a very real sense, we took a big step backward. The screen is redrawn by the server and returned to the user with each operation. Each and every user interaction (ignoring client-side scripting for the moment because it was not immediately available to the first web developers) required a call to a server to do the heavy lifting. See, we are back to the mainframe way of doing things, more or less! We didn’t all just lose our minds overnight, of course; there were some good reasons for doing this. Avoidance of “DLL Hell,” the phenomenon in the Windows world where library versions conflict and cause all sorts of headaches, was certainly one of them. Another reason was the need to distribute applications. When an application runs on a centralized server, it can be accessed from any PC with a web browser without having to first install it. Another good reason was the relative ease of application development. At least in the beginning when webapps were fairly simple things done with little more than HTML and simple back-end CGI programs, almost anyone could quickly and easily pick it up. The learning curve was not all that high, even for those who had not done much application development before. Of course, the Web grew up mighty quick! In what seemed like the blink of an eye, we moved from Figure 1-3 to Figure 1-4. Figure 1-4. Slashdot, circa 1998 Now, that certainly looks a bit better, from a visual standpoint for sure. In addition to just the visual quality, we had a more robust palette of UI widgets available like dropdowns, radio buttons, checkboxes, and so forth. In many ways it was even better than the fat clients that preceded the CHAPTER 1 ■ AJAX: THE BRAVE NEW WORLD 7 6951ch01 7/7/06 8:11 AM Page 7 rise of the Web because “multimedia” presentation was now becoming the norm. Graphics started to become a big part of what we were doing, so visually things were looking a lot better. What about those pesky user interactions, though? Yes, you guessed it: we were still redrawing the entire screen each time at this point. The beginnings of client-side scripting emerged though, and this allowed at least some functionality to occur without the server, but by and large it was still two-tier architecture: a view tier and, well, the rest! For a while we had frames too, which alleviated that problem to some degree, but that was really more a minor divergence on the path than a contributor to the underlying pattern. Before you could say “Internet time,” though, we found ourselves in the “modern” era of the Web, or what we affectionately call “today” (see Figure 1-5). Figure 1-5. The “modern” Web—omnytex.com as the example So, at least visually, as compared to the fat clients we were largely using throughout the late ’80s and early ’90s, we are now at about the same point, and maybe even a bit beyond that arguably. What about the UI elements available to us? Well, they are somewhere in the middle. We have radio buttons and checkboxes and dropdowns and all that, but they are not quite as powerful as their fat-client counterparts. Still, it is clearly better than the text regions we had before the Web. But the underlying problem that we have been talking about all along remains: we are still asking the server to redraw entire screens for virtually every little user event and still asking the server to do the vast majority of the work of our application. We have evolved slightly from the earlier incarnations of the Web to the extent that client-side scripting is now available. So in fact, in contrast to how it was just a few years ago, not every user event requires a server call. Simple things like trivial data entry validations and such are now commonly performed on the CHAPTER 1 ■ AJAX: THE BRAVE NEW WORLD8 6951ch01 7/7/06 8:11 AM Page 8 client machine, independent of the server. Still, the fact remains that most events do require intervention by the server, whether or not that is ideal. Also, where a user has scripting dis- abled, good design dictates that the site should “degrade” gracefully, which means the server again takes on most of the work. At this point I would like to introduce a term I am fond of that I may or may not have invented (I had never heard anyone use it before me, but I cannot imagine I was the first). The term is the “classic” Web. The “classic” Web to me means the paradigm where the server, for nearly every user event, redraws the entire screen. This is how webapps have been built for about 15 years now, since the Web first began to be known in a broad sense. We will be talking about the classic Web versus the modern Web for the remainder of this chapter. Before that, though, going back to our timeline, do you see the pattern? We started with centralized applications and complete redrawing of the screen in response to every single user action. Then we went to fat clients that largely ran locally and only updated the relevant por- tion of the screen. Then we went back to centralized applications, and also back to the central machine redrawing the entire screen. So, what comes next? Well, simply put, the pendulum is beginning to swing right back the other way again, and in a big way! What Is “Wrong” with the Classic Web? In many ways, absolutely nothing! In fact, there is still a great deal of value to that way of designing webapps. The classic Web is great for largely linear application flows, and is also a wonderful medium for delivering information in an accessible way. It is easy for most people to publish information and to even create rudimentary applications with basic user interac- tions. The classic Web is efficient, simple, ubiquitous, and accessible to most people. It is not, however, an ideal environment for developing complex applications. The fact that people have been able to do so to this point is a testament to the ingenuity of engineers rather than an endorsement of the Web as an application distribution medium! It makes sense to differentiate now between a “webapp” and a “web site,” as summarized in Table 1-1. Table 1-1. Summary Comparison of “Webapps” vs. “Websites” Webapps Websites Designed with much greater user interaction Very little user interaction aside from navigation in mind from document to document Main purpose is to perform some function Main purpose is to deliver information, period. or functions, usually in real time, based on user inputs Uses techniques that require a lot more Tends to be created for the lowest common of the clients accessing them denominator in terms of client capabilities Accessibility tends to take a back seat to Accessibility is usually considered and functionality out of necessity and the simple implemented to allow for the widest possible fact that it’s hard to do complex and yet audience. accessible webapps Tends to be more event-based and nonlinear Tends to be somewhat linear with a path the user is generally expected to follow with only minor deviations CHAPTER 1 ■ AJAX: THE BRAVE NEW WORLD 9 6951ch01 7/7/06 8:11 AM Page 9 There are really two different purposes served by the Web at large. One is to deliver infor- mation. In this scenario, it is very important that the information be delivered in a manner that is readily accessible to the widest possible audience. This means not only people with dis- abilities who are using screen readers and such devices, but also those using more limited capability devices like cell phones, PocketPCs, and kiosk terminals. In such situations, there tends to be no user interactions aside from jumping from static document to static document, or at most very little interaction via simple fill-out forms. This mode of operation for the Web, if you will, can be classified as websites. The webapps, on the other hand, have a wholly different focus. They are not concerned with simply presenting information, but in performing some function based on what the user does and what data the user provides. The user can be another automated system in many cases, but usually we are talking about real flesh-and-blood human beings. Webapps tend to be more complex and much more demanding of the clients that access them. In this case, “clients” refer to web browsers. This does not have to be true. There are indeed some very complex webapps out there that do not require any more capability of clients than a website does. While it clearly is not impossible to build complex applications in the “website” mode, it is limiting and more difficult to do well in terms of user-friendliness, and it tends to require sacrifices in terms of capabilities or robustness of the capabilities provided. This is the problem with the classic model: you generally have to design to the lowest common denominator, which severely limits what you can do. Let’s think a moment about what the lowest common denominator means in this context. Consider what you could and could not use to reach the absolute widest possible audience out there today. Here is a list of what comes to mind: • Client-side scripting: Nope, you could not use this because many mobile devices do not yet have scripting support, or are severely limited. This does not even consider those people on full-blown PCs who simply choose to disable scripting for security or other reasons. • Cascading Stylesheets (CSS): You could use it, but you would have to be very careful to use an older specification to ensure most browsers would render it properly—none of the fancier CSS 2.0 capabilities for instance. • Frames: No, frames are not universally supported, especially on many portable devices. Even when they are supported you need to be careful because a frame is essentially like having another browser instance in terms of memory (and in some cases it very literally is another browser instance), and this can be a major factor in mobile devices. • Graphics: Graphics can be tricky in terms of accessibility because they tend to convey more information than an ALT attribute can. So, some of the meaning of the graphic can easily be lost for those with disabilities, no matter how vigilant you are to help them. • Newer HTML specs: There are still many people out there using older browsers that may not even support HTML 4.01, so to be safe you will probably want to code to HTML 3.0. You will lose some capabilities obviously in doing so. CHAPTER 1 ■ AJAX: THE BRAVE NEW WORLD10 6951ch01 7/7/06 8:11 AM Page 10 fa938d55a4ad028892b226aef3fbf3dd Probably the most important element here is the lack of client-side scripting. Without client-side scripting, there are simply so many possibilities that are not available to you as a developer. Most important in the context of this book is the fact that you have virtually no choice but to have the server handle every single user interaction. You may be able to get away with some meta-refreshes in frames in some cases, or perhaps other tricks of the trade, but frames too are on the list, so you might not even have that option! You may be wondering, “What is the problem with the server rendering entire pages?” Certainly there are benefits, and the inherent security of being in complete control of the runtime state of the application (i.e., the user can’t hack the code) is a big one. Not having to incur the delay of downloading the code to the client is another. However, there are indeed some problems that in many cases overshadow the benefits. Perhaps the most obvious is the load on the server. Asking a server to do all this work on behalf of the client many times over across a number of simultaneous requests means that the server needs to be more robust and capable than it might otherwise need to be. This all translates to dollars and cents in the long run because you will have to purchase more server power to handle the load. Now, many peo- ple have the “just throw more hardware at it” mentality, and we are indeed in an age where that works most of the time. But that is much like saying that because we can throw bigger and bigger engines in cars to make them go faster then that’s exactly what we should always do when we need or want more speed. In fact, we can make cars go faster by making a smaller engine more efficient in design and execution, which in many ways is much more desirable— that is, if you like clean, fresh air to breathe! Perhaps an even better metaphor would be to say it is like taking a mid-sized car and con- tinually adding seats tied to it around the outside to allow for more people to ride “in” the car rather than trying to find a more efficient way for them to get where they are going. While this duct-tape solution might work for a while, eventually someone is going to fall off and get crushed by the 18-wheeler driving behind us! Another problem with the server-does-it-all approach is that of network traffic. Network technology continues to grow in leaps and bounds at a fantastic rate. Many of us now have broadband connections in our homes that we could not fully saturate if we tried (and I for one have tried!). However, that does not mean we should have applications that are sending far more information per request than they need to. We should still strive for thriftiness, should we not? The other big problem is simply how the user perceives the application. When the server has to redraw the entire screen, it generally results in a longer wait time to see the results, not to mention the visual redrawing that many times occurs in webapps, flickering, and things of that nature. These are things users universally dislike in a big way. They also do not like losing everything they entered when something goes wrong, which is another common failing of the classic model. At the end of the day, the classic model still works well on a small scale, and for delivering mostly static information, but it doesn’t scale very well and it doesn’t deal with the dynamic nature of the Web today nearly as well. In this context, “scale” refers to added functionality in the application, not simultaneous request handling capability (although it is quite possible that is in play, too). If things do not work as smoothly, or if breakages result in too much lost, or if perceived speed is diminished, then the approach didn’t scale well. CHAPTER 1 ■ AJAX: THE BRAVE NEW WORLD 11 6951ch01 7/7/06 8:11 AM Page 11 The classic model will continue to serve us well for some time to come in the realm of websites, but in the realm of webapps—the realm you are likely interested in if you are reading this book—its demise is at hand, and its slayer is the hero of our tale: Ajax! Enter Ajax Ajax (see Figure 1-6…now you’ll always know what code and architectures would look like personified as a super hero!) came to life, so to speak, at the hands of one Jesse James Garrett of Adaptive Path (www.adaptivepath.com). I am fighting my natural urge to make the obvious outlaw jokes here! Mr. Garrett wrote an essay in February 2005 (you can see it here: www.adaptivepath.com/publications/essays/archives/000385.php) in which he coined the term Ajax. Figures 1-7 through 1-9 show examples of Ajax-enabled applications. Figure 1-6. Ajax to the rescue! Figure 1-7. Backbase, a commercial product for creating Ajax applications, shows off their prod- uct in this flight-booking application. CHAPTER 1 ■ AJAX: THE BRAVE NEW WORLD12 6951ch01 7/7/06 8:11 AM Page 12 Ajax, as I’d be willing to bet my dog you know already (I don’t have a dog, but I will buy one and give it to you if you don’t know what Ajax stands for! OK, not really) stands for Asynchronous JavaScript and XML. The interesting thing about Ajax, though, is that it doesn’t have to be asynchronous (but virtually always is), doesn’t have to involve JavaScript (but virtu- ally always does), and doesn’t need to use XML at all (but probably does half the time). In fact, one of the most famous Ajax examples, Google Suggest, doesn’t pass back XML at all! The fact is that it does not even pass back data per se; it passes back JavaScript that contains data! Don’t worry if that doesn’t make much sense, because it will by the end of this book. Figure 1-8. Google Reader, now in beta, is a rather good Ajax-enabled RSS reader. Ajax is, at its core, an exceedingly simple, and by no stretch of the imagination original, concept: it is not necessary to refresh the entire contents of a web page for each user interac- tion, or each “event,” if you will. When the user clicks a button, it is no longer necessary to ask the server to render an entirely new page, as is the case with the classic Web. Instead, you can define regions on the page to be updated, and have much more fine-grained control over user events as well. No longer are you limited to simply submitting a form or navigating to a new page when a link is clicked. You can now do something in direct response to a non-submit button being clicked, a key being pressed in a text box—in fact, to any event happening! The server is no longer completely responsible for rendering what the user sees; some of this logic is now performed in the user’s browser. In fact, in a great many cases it is considerably better to simply return a set of data and not a bunch of markup for the browser to display. As we traced along our admittedly rough history of application development, we saw that the classic model of web development is in a sense an aberration to the extent that we actually had it right before then! CHAPTER 1 ■ AJAX: THE BRAVE NEW WORLD 13 6951ch01 7/7/06 8:11 AM Page 13 Ajax is a return to that thinking. Notice I said “thinking.” That should be a very big clue to you about what Ajax really is. It is not a specific technology, and it is not the myriad toolkits available for doing Ajax, and it is not the XMLHttpRequest object (which we will get to in a moment). It is a way of thinking, an approach to application development, a mind-set. The interesting thing about Ajax is that it is in no way, shape, or form new; only the term used to describe it is. I was recently reminded of this fact at the Philadelphia Java Users Group. A speaker by the name of Steve Banfield was talking about Ajax, and he said (paraphrasing from memory): “You can always tell someone who has actually done Ajax because they are pissed that it is all of a sudden popular.” This could not be more true! I was one of those people doing Ajax years and years ago; I just never thought what I was doing was anything special and hence did not give it a “proper” name. Mr. Garrett holds that distinction. Figure 1-9. Num Sum is an Ajax-based spreadsheet application. I mentioned that I personally have been doing Ajax for a number of years, and that is true. What I did not say, however, is that I have been using XML or that I have been using the XMLHttpRequest object. I will reveal what I was using all those years ago when we discuss alter- natives to Ajax, but the important point here is that the approach that is at the heart of Ajax is nothing new as it does not, contrary to its very own name, require any specific technologies (aside from client-side scripting, which is, with few exceptions, required of an Ajax or Ajax-like solution). When you get into the Ajax frame of mind, which is what we are really talking about, you are no longer bound by the rules of the classic Web. You can now take back at least some of the power the fat clients offered, while still keeping the benefits of the Web in place. Those bene- fits begin, most important perhaps, with the ubiquity of the web browser. CHAPTER 1 ■ AJAX: THE BRAVE NEW WORLD14 6951ch01 7/7/06 8:11 AM Page 14 Have you ever been at work and had to give a demo of some new fat client app, for exam- ple, a Visual Basic app, that you ran on a machine you have never touched before? Ever have to do it in the boardroom in front of top company executives? Ever had that demo fail miserably because of some DLL conflict you couldn’t possibly anticipate (Figure 1-10)! You are a devel- oper, so the answer to all of those questions is likely yes (unless you work in the public sector, and then it probably was not corporate executives, but you get the point). If you have never done Windows development, you may not have had these experiences. You will have to take my word for it when I say that such situations were, for a long time, much more common than any of us would have liked. With a web-based application, this is generally not a concern. Ensure the PC has the correct browser and version, and off you go 98 percent of the time. The other major benefit of a webapp is distribution. No longer do you need a 3-month shakedown period to ensure your new application does not conflict with the existing suite of corporate applications. An app running in a web browser, security issues aside, will not affect, or be affected, by any other application on the PC (and I am sure we all have war stories about exceptions to that, but they are just that: exceptions!). Figure 1-10. We’ve all been there. Live demos and engineers do not mix! Of course, you probably knew those benefits already, or you probably wouldn’t be inter- ested in web development in the first place. The Flip Side of the Coin Sounding good so far, huh? It is not all roses in Ajax land, however, and Ajax is not without its problems. Some of them are arguably only perceived problems, but others are concrete. First and foremost, in my mind at least, is accessibility. You will lose at least some accessibility in your work by using Ajax because devices like screen readers are designed to read an entire page, and since you will no longer be sending back entire pages, screen readers will have trouble. My understanding is that some screen readers can deal with Ajax to some degree, largely depending on how Ajax is used (if the content is literally inserted into the Doc- ument Object Model, or DOM, makes a big difference). In any case, extreme caution should be used if you know people with disabilities are a target audience for your application, and you will seriously want to consider (and test!) whether Ajax will work in your situation. I am cer- tain this problem will be addressed better as time goes on, but for now it is definitely a concern. Even still, there are some things you can do to improve accessibility: CHAPTER 1 ■ AJAX: THE BRAVE NEW WORLD 15 6951ch01 7/7/06 8:11 AM Page 15 • Put a note at the top of the page that says the page will be updated dynamically. This will give the user the knowledge that they may need to periodically request a reread of the page from the screen reader to hear the dynamic updates. • Depending on the nature of the Ajax you are using on a page, use alert() pop-ups when possible as these are read by a screen reader. This is a reasonable enough sugges- tion for things like Ajax-based form submission that will not be happening too frequently, but obviously if you have a timed, repeating Ajax event, this suggestion would not be a good one. • Remember that it is not only the blind who have accessibility needs; it can be sighted people as well. For them, try to use visual cues whenever possible. For instance, briefly highlighting items that have changed can be a big help. Some people call this the “Yel- low Fade Effect,”1 whereby you highlight the changed item in yellow and then slowly fade it back to the nonhighlighted state. Of course, it does not have to be yellow, and it does not have to fade, but the underlying concept is the same: highlight changed infor- mation to provide a visual cue that something has happened. Remember that changes caused by Ajax can sometimes be very subtle, so anything you can do to help people notice them will be appreciated. Another disadvantage to many people is added complexity. Many shops do not have in- house the client-side coding expertise Ajax requires (the use of toolkits that make it easier notwithstanding). The fact is, errors that occur client-side are still, by and large, harder to track down than server-side problems, and Ajax does not make this any simpler. For example, View Source does not reflect changes made to the DOM (there are some tools available for Firefox that actually do allow this). Another issue is that Ajax applications will many times do away with some time-honored web concepts, most specifically back and forward buttons and bookmarking. Since there are no longer entire pages, but instead fragments of pages being returned, the browser cannot bookmark things in many cases. Moreover, the back and forward buttons cease to have the same meanings because they still refer to the last URL that was requested, and Ajax requests almost never are included (requests made through the XML- HttpRequest are not added to history, for example, because the URL generally does not change, especially when the method used is POST). All of these disadvantages, except for perhaps accessibility to a somewhat lesser extent, have solutions, and we will see some of them later in the example apps. They do, however, rep- resent differences in how webapps are developed for most developers, and they cause angst for many people. So they are things you should absolutely be aware of as you move forward with your Ajax work. Why Is Ajax a Paradigm Shift? On the Road to RIAs Ajax does in fact represent a paradigm shift for some people (even most people, given what most webapps are today) because it can fundamentally change the way you develop a webapp. More important perhaps is that it represents a paradigm shift for the user, and in fact it is the users who will drive the adoption of Ajax. Believe me; you will not long be able to ignore Ajax as a weapon in your toolbox. CHAPTER 1 ■ AJAX: THE BRAVE NEW WORLD16 1 The term “Yellow Fade Effect” seems to have originated with a company called 37signals, as seen in this article: www.37signals.com/svn/archives/000558.php. 6951ch01 7/7/06 8:11 AM Page 16 Put a non-Ajax webapp in front of a user, and then put that same app using Ajax tech- niques in front of them, and guess which one they are going to want to use all day nine times out of ten? The Ajax version! They will immediately see the increased responsiveness of the application and will notice that they no longer need to wait for a response from the server while they stare at a spinning browser logo wondering if anything is actually happening. They will see that the application alerts them on the fly of error conditions they would have to wait for the server to tell them about in the non-Ajax webapp. They will see functionality like type- ahead suggestions and instantly sortable tables and master-detail displays that update in real time—things that they would not see in a non-Ajax webapp. They will see maps that they can drag around like they can in the full-blown mapping applications they spent $80 on before. All of these things will be obvious advantages to the user. Users have become accustomed to the classic webapp model, but when confronted with something that harkens back to those fat- client days in terms of user-friendliness and responsiveness, there is almost an instantaneous realization that the Web as they knew it is dead, or at least should be! If you think about many of the big technologies to come down the pipe in recent years, it should occur to you that we technology folks rather than the users were driving many of them. Do you think a user ever asked for an Enterprise JavaBean (EJB)-based application? No, we just all thought it was a good idea (how wrong we were there!). What about web services? Remember when they were going to fundamentally change the way the world of application construction worked? Sure, we are using them today, but are they, by and large, much more than an interface between cooperating systems? Not usually. Whatever happened to Universal Description, Discovery, and Integration (UDDI) directories and giving an application the abil- ity to find, dynamically link to, and use a registered service on the fly? How good did that sound? To us geeks it was the next coming, but it didn’t even register with users. Ajax is different, though. Users can see the benefits. They are very real and very tangible to them. In fact, we as technology people, especially those of us doing Java web development, may even recoil at Ajax at first because more is being done on the client, which is contrary to what we have been drilling into our brains all these years. After all, we all believe scriptlets in JavaServer Pages (JSPs) are bad, eschewing them in favor of custom tags. The users do not care about elegant architectures and separation of concerns and abstractions allowing for code reuse. Users just want to be able to drag the map around in Google Maps (Figure 1-11) and have it happen real time without waiting for the whole page to refresh like they do (or did any- way) when using Yahoo!’s mapping solution. The difference is clear. They want it, and they want it now (come on, we’re adults here!) Ajax is not the only new term floating around these days that essentially refers to the same thing. You may have also heard of Web 2.0 and RIAs. RIA is a term I particularly like, and I will discuss it a bit. RIA stands for Rich Internet Application. Although there is no formal definition with which I am familiar, most people get the gist of its meaning without having to Google for it. In short, the goal of an RIA is to create an application that is web based—that is, it runs in a web browser but looks, feels, and functions more like a typical fat-client application than a “typical” website. Things like partial-page updates are taken for granted, and hence Ajax is always involved in RIAs (although what form of Ajax is involved can vary; indeed you may not find the XMLHttpRequest object, the prototypical Ajax solution, lurking about at all!). These types of applications are always more user-friendly and better received by the user commu- nity they service. In fact, your goal in building RIAs should be for users to say, “I didn’t even know it was a webapp!” CHAPTER 1 ■ AJAX: THE BRAVE NEW WORLD 17 6951ch01 7/7/06 8:11 AM Page 17 Figure 1-11. Google Maps Gmail (Figure 1-12) is a good example of an RIA, although even it isn’t perfect because while it has definite advantages over a typical website, it still looks and feels very much like a web page. Microsoft’s Hotmail is another good example. Figure 1-12. Gmail, an Ajax webmail application from Google CHAPTER 1 ■ AJAX: THE BRAVE NEW WORLD18 6951ch01 7/7/06 8:11 AM Page 18 You may have noticed that many of the Ajax examples shown thus far have been from Google. That is not a coincidence. Google has done more to bring Ajax to the forefront of people’s minds than anyone else. They were not the first to do it, or even the best necessarily, but they certainly have been some of the most visible examples and have really shown people what possibilities Ajax opens up. Enough of the theory, definitions, history, and philosophy behind Ajax and RIAs and all that. Let’s go get our hands dirty with some actual code! Let’s Get to It: Our First Ajax Example This book aims to be different from most Ajax books in that it is based around the concept of giving you concrete examples to learn from, explaining them, explaining the decisions behind them (even the debatable ones), and letting you get your hands dirty with code. We are not going to spend a whole lot of time looking at UML diagrams, sequence diagrams, use case diagrams, and the like. You are more than welcome to pick up any of the fine UML books out there for that. With that in mind, we are not going to waste any more time telling you what Ajax is, why it is the greatest thing since sliced bread, where the name came from, or any of that. Instead, we are going to jump right into some code! This first example is somewhat unique in that it doesn’t require Java. In fact, it does not require a server at all. Rest assured that all the other examples in this book do, as the title sug- gests. But we want to cover a simple Ajax app without server interaction first, just to get some of the basics covered, so here goes (Listing 1-1). Listing 1-1. Our First Real Ajax Application! Simple Non-Server AJAX Example Our first simple AJAX example

Make a selection here:


In response, a list of characters will appear here:
Figure 1-13 shows what it looks like on the screen (don’t expect much here, folks!). CHAPTER 1 ■ AJAX: THE BRAVE NEW WORLD20 6951ch01 7/7/06 8:11 AM Page 20 Figure 1-13. Note that there is no content in the second dropdown because nothing has been selected yet in the first. As you can see, there is no content in the second dropdown initially. This will be dynami- cally populated once a selection is made in the first, as shown in Figure 1-14. Figure 1-14. A selection has been made in the first dropdown, and the contents of the second have been dynamically created from what was returned by the “server.” CHAPTER 1 ■ AJAX: THE BRAVE NEW WORLD 21 6951ch01 7/7/06 8:11 AM Page 21 Figure 1-14 shows that when a selection is made in the first dropdown, the contents of the second are dynamically updated. In this case we see characters from the greatest television show ever, “Babylon 5” (don’t bother arguing, you know I’m right! And besides, you’ll get your chance to put in your favorites later!). Now let’s see how this “magic” is accomplished. Listing 1-1 shows the first page of our simple Ajax example, which performs a fairly typical Ajax-type function: populate one . With Ajax, none of that is necessary. Let’s walk through the code and see what is going on. Note that this is not meant to be a robust, production-quality piece of code. It is meant to give you an understanding of basic Ajax techniques, nothing more. There is no need to write in with all the flaws you find! First things first: the markup itself. In our we have little more than some text and two element (see Listing 1-2). This element, and we are naming it selShow so we can easily get at it later. Listing 1-2. The First You will notice the JavaScript event handler attached to this element. Any time the value of the element… sort of (Listing 1-3). Listing 1-3. The
Where the New
CHAPTER 1 ■ AJAX: THE BRAVE NEW WORLD22 6951ch01 7/7/06 8:11 AM Page 22 It is indeed an empty element, complete with