Электронная библиотека “Либрус” ( http://librus.ru ) Научно-техническая библиотека электронных книг. Первоначально задуманная как хранилище компьютерной литературы, в настоящий момент библиотека содержит книжные издания по различным областям знания (медицинские науки, техника, гуманитарные науки, домашнее хозяйство, учебная литература и т.д.). Серьезность научно-технических e-book'ов разбавляет раздел развлекательной литературы (эротика, комиксы, задачи и головоломки). Основной целью проекта является ознакомление читателей с многообразием книгопечатной продукции и помощь в выборе действительно стоящей книги для приобретения у законных издателей, их представителей или в соответствующих организациях торговли. Для покупки через Internet мы рекомендуем воспользоваться услугами интернет-магазина “Озон”. ВНИМАНИЕ! Данный файл представлен исключительно в ознакомительных целях! После ознакомления с данной книгой Вы обязаны удалить ее с Вашего компьютера. В случае несоблюдения данного обязательства, Вы нарушите закон "Об авторском праве и смежных правах". Все авторские права сохраняются за правообладателем. По его требованию доступ к данному электронному документу будет перекрыт. Однако, таким образом, тысячи потенциальных покупателей так и не узнают о, возможно, нужной и полезной книге. Авторам и издательствам Если Вы заинтересованы в рекламе и продвижении Ваших книг на бескрайних сетевых просторах мы с удовольствием включим их в наш каталог. Bulletproofing Web Applications Adam Kolawa, Wendell Hicken, and Cynthia Dunlop Published by M&T Books An imprint of Hungry Minds, Inc. 909 Third Avenue New York, NY 10022 www.hungryminds.com Copyright © 2002 Hungry Minds, Inc. All rights reserved. No part of this book, including interior design, cover design, and icons, may be reproduced or transmitted in any form, by any means (electronic, photocopying, recording, or otherwise) without the prior written permission of the publisher. Library of Congress Control Number: 2001092904 ISBN: 0-7645-4866-2 Printed in the United States of America 10 9 8 7 6 5 4 3 2 1 1B/RU/RS/QR/IN Distributed in the United States by Hungry Minds, Inc. Distributed by CDG Books Canada Inc. for Canada; by Transworld Publishers Limited in the United Kingdom; by IDG Norge Books for Norway; by IDG Sweden Books for Sweden; by IDG Books Australia Publishing Corporation Pty. Ltd. for Australia and New Zealand; by TransQuest Publishers Pte Ltd. for Singapore, Malaysia, Thailand, Indonesia, and Hong Kong; by Gotop Information Inc. for Taiwan; by ICG Muse, Inc. for Japan; by Intersoft for South Africa; by Eyrolles for France; by International Thomson Publishing for Germany, Austria, and Switzerland; by Distribuidora Cuspide for Argentina; by LR International for Brazil; by Galileo Libros for Chile; by Ediciones ZETA S.C.R. Ltda. for Peru; by WS Computer Publishing Corporation, Inc., for the Philippines; by Contemporanea de Ediciones for Venezuela; by Express Computer Distributors for the Caribbean and West Indies; by Micronesia Media Distributor, Inc. for Micronesia; by Chips Computadoras S.A. de C.V. for Mexico; by Editorial Norma de Panama S.A. for Panama; by American Bookshops for Finland. For general information on Hungry Minds’ products and services please contact our Customer Care department within the U.S. at 800-762-2974, outside the U.S. at 317- 572-3993 or fax 317-572-4002. For sales inquiries and reseller information, including discounts, premium and bulk quantity sales, and foreign-language translations, please contact our Customer Care department at 800-434-3422, fax 317-572-4002 or write to Hungry Minds, Inc., Attn: Customer Care Department, 10475 Crosspoint Boulevard, Indianapolis, IN 46256. For information on licensing foreign or domestic rights, please contact our Sub-Rights Customer Care department at 212-884-5000. For information on using Hungry Minds’ products and services in the classroom or for ordering examination copies, please contact our Educational Sales department at 800- 434-2086 or fax 317-572-4005. For press review copies, author interviews, or other publicity information, please contact our Public Relations department at 317-572-3168 or fax 317-572-4168. For authorization to photocopy items for corporate, personal, or educational use, please contact Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, or fax 978-750-4470. LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND AUTHOR HAVE USED THEIR BEST EFFORTS IN PREPARING THIS BOOK. THE PUBLISHER AND AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS BOOK AND SPECIFICALLY DISCLAIM ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. THERE ARE NO WARRANTIES WHICH EXTEND BEYOND THE DESCRIPTIONS CONTAINED IN THIS PARAGRAPH. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES REPRESENTATIVES OR WRITTEN SALES MATERIALS. THE ACCURACY AND COMPLETENESS OF THE INFORMATION PROVIDED HEREIN AND THE OPINIONS STATED HEREIN ARE NOT GUARANTEED OR WARRANTED TO PRODUCE ANY PARTICULAR RESULTS, AND THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY INDIVIDUAL. NEITHER THE PUBLISHER NOR AUTHOR SHALL BE LIABLE FOR ANY LOSS OF PROFIT OR ANY OTHER COMMERCIAL DAMAGES, INCLUDING BUT NOT LIMITED TO SPECIAL, INCIDENTAL, CONSEQUENTIAL, OR OTHER DAMAGES. Trademarks: Hungry Minds, the Hungry Minds logo, M&T Books, the M&T Books logo, and Professional Mindware are trademarks or registered trademarks of Hungry Minds, Inc. 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. Hungry Minds, Inc., is not associated with any product or vendor mentioned in this book. Hungry MindsTM is a trademark of Hungry Minds, Inc. M BooksTM is a trademark of Hungry Minds, Inc. Credits Acquisitions Manager: Chris Webb Senior Project Editor: Jodi Jensen Technical Editors: Matt Haughey Matt Hamer: Development Editors Kezia Endsley: Susan Hobbs Gus Miklos: Copy Editor: Kate Talbot Editorial Manager: Mary Beth Wakefield Senior Vice President, Technical Publishing: Richard Swadley Vice President and Publisher: Joseph B. Wikert Project Coordinator: Dale White Graphics and Production Specialists: Sean Decker, Stephanie Jumper, Gabriele McCann, Laurie Petrone, Jill Piscitelli, Betty Schulte, Julie Trippetti, Jeremey Unger, Mary Virgin, Erin Zeltner Quality Control Technicians: David Faust, Susan Moritz, Carl Pierce Senior Permissions Editor: Carmen Krikorian Media Development Specialist: Megan Decraene Proofreading and Indexing: TECHBOOKS Production Services Cover Image: © Noma/Images.com Special Help: Sara Shlaer About the Authors Adam Kolawa is the CEO of ParaSoft Corporation, a leading provider of software productivity solutions. Kolawa came to the United States from Poland in 1983 to pursue a Ph.D. at the California Institute of Technology. In 1987, he and a group of fellow graduate students founded ParaSoft with the hopes of creating value-added products that could significantly improve the software development process. Kolawa’s years of experience with various software development processes has resulted in his unique insight into the high-tech industry and his uncanny ability to successfully identify technology trends. As a result, he has orchestrated the development of several successful commercial software products to meet growing industry needs to improve software quality — often before the trends have been widely accepted. Kolawa has been granted seven patents for the technologies behind these innovative tools. In addition, Kolawa has contributed to and written commentary pieces and technical articles for various leading publications such as Software Development, Java Report and SD Times. He has also presented on software quality, trends, and development issues at industry conferences including JavaOne, Quality Week, Linux Expo, and Software Development. Kolawa holds a Ph.D. in theoretical physics from the California Institute of Technology. In 2001, Kolawa was awarded the Los Angeles Ernst & Young’s Entrepreneur of the Year Award in the software category. Wendell Hicken is the Vice President of Advanced Research and Development for ParaSoft Corporation. In his 12 years with the company, he has played a major role in all facets of product development — from the initial design phase, through development, and up to final product release. He has been essential to the conception, implementation, and continued development of products such as WebKing, RuleWizard, CodeWizard, Insure++, and the technologies that drive them. Hicken is also heavily involved in the development of many new Web-based innovations. Hicken holds a BS in Engineering and Applied Science from the California Institute of Technology. Cynthia Dunlop is a Senior Technical Author for ParaSoft Corporation. Since 1998, Dunlop has been responsible for crafting ParaSoft product manuals and technical papers. Dunlop can also be credited with authoring numerous technical articles about issues related to software development. Prior to joining ParaSoft, Dunlop worked as a writing instructor at Washington State University. Dunlop holds an MA in English from Washington State University and a BA in English from UCLA. Foreword Testing and QA always get the short end of the stick — but they don’t have to. On a typical project (if such a thing exists), the software development lifecycle is expanded at the beginning and compressed at the end. Business requirements take longer to gather than anyone expects as developers, customers, and end users struggle to define their expectations. Planners underestimate the time necessary to translate those requirements into application models. When the programmers finally begin coding, the project is already behind schedule. From the outset, the programmers rush through their work, under pressure from managers and customers to deliver the software according to the original schedule. Through Herculean effort, the programmers accomplish their task; but under constant pressure, they’re prone to cut corners. The one place this is most likely to happen is in the debugging process. When they hand over the project to a quality assurance (QA) team, shortcuts often happen there as well: Although it’s rarely stated overtly, QA’s job is to approve the code — not find fault with it, especially nontrivial design flaws that might require significant reworking of the application and delay its deployment. This debugging/testing reality is especially true of server-side Web apps. Few developers understand how to test or troubleshoot Web apps effectively, and under the constant pressure to deliver, deliver, deliver, they don’t have time to learn how to leverage this new paradigm. After all, the top brass says, the important job is to make the application live so that we can engage in competitive e-business — you can swat the bugs and improve performance later, right? Wrong, and that’s where Bulletproofing Web Applications offers a service to the software development community by providing techniques and best practices for integrating testing and QA into the complete Web development lifecycle — where they belong. Alan Zeichick Editor-in-Chief BZ Media’s SD Times Preface This book discusses strategies for bulletproofing Web applications. By Web application, we mean an enterprise system running on a server, accessed by a client that is typically a Web browser. These kinds of applications are usually associated with the HTTP protocol and use HTML for at least part of their interface. By bulletproofing, we mean making sure your application is robust, scalable, efficient, and reliable. Many people viewed Web development as child’s play during the early days of small static Web sites. It’s now obvious, however, that Web development is as complex as traditional software development — if not more so. As a result of this complexity, it’s almost impossible to produce a completely reliable Web application unless you implement (and continue to follow) a well-defined development process that incorporates a set of vital bulletproofing practices. That’s where this book comes in. We, the authors, have spent many years at ParaSoft Corporation working on technologies that help companies improve the reliability of their software. During this time, we have had the opportunity to observe many different companies’ software development processes and gain a good understanding of what practices can be used to increase the reliability of many types of software products. Based on our extensive experience working with Web applications at several levels, we have developed what we feel is a useful approach to the challenge of developing bulletproof Web applications. This book describes that approach and suggests ways that you can apply it to your own development process and projects. Intended Audience This book is intended for people who are already familiar with Web applications, from developers to Quality Assurance testers to managers of Web development projects. Although we review the basic ideas, we don’t show you everything you need to know to create Web applications. We do show you development and testing practices that you can apply to your application, and we give you ideas for improving the processes you use during development, including some tips on how to ensure that team members leverage one another’s work (rather than step on each others’ toes). What You’ll Learn We describe and demonstrate a variety of bulletproofing practices that will help you predict and prevent potential problems, detect and remove existing problems, and construct your application in such a way that it can recover if an error occurs. Many of these practices are based on practices that have proven successful for traditional software development and were extended to meet the unique needs and challenges of Web development. Although there is no “silver bullet” for reliable Web applications, there are a number of techniques and tools that can significantly improve application reliability. Each time we introduce a general practice, we show you a variety of ways to perform that practice (including manual solutions, scripting solutions, and automatic tools). We emphasize automating your procedures whenever possible. We stress automation so strongly because we’ve seen how it can improve both reliability and efficiency, enabling team members to spend their time improving the application instead of putting out fires and performing tedious tasks. To keep our discussions concrete, we refer to specific languages and tools. Where we claim that you can write scripts to automate certain tasks, we usually give examples that you can actually run yourself. This is not intended to limit you to the scripts or tools we show but to provide illustrations of ideas we hope you can apply to improve your own application. Beginning with Chapter 4, we develop a sample e-commerce site (“The Online Grocer”) so that we can provide concrete examples in the discussions throughout the book. The primary version is developed using Java servlets and the Apache Web server. Additional versions using JSP, WML, XML, and other technologies are introduced in Part III. The implementation, however, is not the key point; the focus is on the methods for building and testing the application. Most of the ideas we discuss apply equally to applications developed using various technologies. Even the specific Java-centered approaches have analogous practices for other languages. How This Book Is Organized This book has been divided into three parts. If you are in a rush to find out more about a specific topic, jump right in to the chapter that seems most applicable. You can always go back to the introductory section later when you have more time. Part I: Getting Started Part I provides an overview of the development process and introduces the Online Grocer Web application that we refer to throughout the rest of the book. If you want to grasp the fundamental development strategies and issues we frequently touch on, we recommend that you read Chapters 1 through 3 before diving into the rest of the book. For details about the Online Grocer application, you can read Chapters 4 through 6. These details are particularly useful if you’re having trouble following the examples mentioned in later chapters. Part II: Bulletproofing Practices Part II provides detailed information about challenges and practices relevant to most Web applications. It includes discussions of strategies such as defensive programming, coding standards, unit testing, functionality testing, content verification, and load testing. Generally speaking, these topics are introduced in the order in which you would encounter them during the development of your application. For the most part, these chapters can be read in any order, although they occasionally reference one another. Part III: Other Technologies Part III discusses “specialty” bulletproofing practices that are primarily applicable to applications using the relevant technology. We start by covering issues related to using databases in Web applications, move to XML and the related technologies of SOAP and Web services, and conclude by discussing components such as EJBs and server- side scripting technologies such as JSP. Appendixes In the appendixes, you’ll find a summary of the key points from our sample programs, procedures, and tools, along with a list of additional resources. Some of these resources provide more information on topics we discuss in depth, whereas others offer a starting point for learning about topics that we touch on but don’t cover in detail. CD-ROM The CD-ROM that accompanies this book includes the sample files referenced in the book — often with more detail than you’ll find in the chapters. We encourage you to use these examples to see our practices in action and to experiment with ways of bringing these practices into your own development process. The CD also contains evaluation versions of many of ParaSoft’s tools, as well as versions of freely available Web development tools. Conventions Throughout the book we use simple conventions common to most technical books. Code examples, or text you would type are entered in a fixed font as follows: sample code We use italic type to indicate a new term that we’re defining, and we use shaded sidebars when we want to provide more detail about concepts mentioned in the text. Icons Used in This Book Icons appear in the text to indicate important or especially helpful items. Here’s a list of the icons and their functions: Note Notes provide additional or critical information and technical data on the current topic. X-Ref Cross-Reference icons point you to someplace else in the book where you can find more information on a particular topic. Tip The Tip icon points you to useful techniques and helpful hints. Caution The Caution icon is your warning of a potential problem or pitfall. On the The On the CD-ROM icon points out a related sample file or CD additional information that you can find on the CD accompanying this book. Feedback We welcome your feedback on any aspect of this book. You can send e-mail to us at [email protected]. We’ve also set up a Web page at www.parasoft.com/bulletproof where you can find any errata, along with additional examples. Acknowledgments This book is the product of many people’s effort and help. We would like to thank the following people for their direct contributions: Sierra Roberts, for making this project a reality and managing the entire process. Jim Clune, for writing Chapters 17 and 18 and reviewing numerous other sections. Marek Kucharski, for writing Chapters 16 and 20. Dr. Roman Salvador, for writing Chapter 19 and contributing to Chapters 7, 8, and 9. Arthur Hicken, for contributing to Chapter 16. Alan Zeichick, for writing the Foreword. Everyone at Hungry Minds who helped us mold our ideas into a presentable book, including Chris Webb for helping us get this book published, Jodi Jensen, for getting this project on track and coordinating its many facets; Susan Hobbs, Kate Talbot, Gus Miklos, Matthew Haughey, Matthew Hamer, and Kezia Endsley for their suggestions and editorial improvements; Carmen Krikorian for obtaining the necessary permissions for the CD; Megan Decraene for her work building and testing the CD; and the graphics and production staffs. We also want to extend a special thanks to everyone at ParaSoft who has played a “behind the scenes” role in the development and quality of this book and the programs on the CD. This includes everyone in our development, quality assurance, marketing, sales, and corporate departments — especially Jenny Ahn, our invaluable Vice President. Last, but certainly not least, we would like to thank our customers for providing the feedback that has shaped our ideas and products.