01 559575 FM.qxd 3/2/04 3:53 PM Page i Jakarta Struts FOR DUMmIES ‰ by Mike Robinson and Ellen Finkelstein 01 559575 FM.qxd 3/2/04 3:53 PM Page ii Jakarta Struts For Dummies® Published by Wiley Publishing, Inc. 111 River Street Hoboken, NJ 07030-5774 Copyright © 2004 by Wiley Publishing, Inc., Indianapolis, Indiana Published by Wiley Publishing, Inc., Indianapolis, Indiana Published simultaneously in Canada No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4447, e-mail: [email protected]. Trademarks: Wiley, the Wiley Publishing logo, For Dummies, the Dummies Man logo, A Reference for the Rest of Us!, The Dummies Way, Dummies Daily, The Fun and Easy Way, Dummies.com, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates in the United States and other countries, and may not be used without written permission. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book. LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REP RESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CRE ATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CON TAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FUR THER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ. For general information on our other products and services or to obtain technical support, 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. Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books. Library of Congress Control Number: 2004101960 ISBN: 0-7645-5957-5 Manufactured in the United States of America 10 9 8 7 6 5 4 3 2 1 1O/RZ/QT/QU/IN 01 559575 FM.qxd 3/2/04 3:53 PM Page iii About the Authors Mike Robinson has been working in the computing field since, well, when minicomputers were popular. He has a master’s degree in computer science and has been an independent Java developer specializing in interactive Web applications since 1998. Mike is an adjunct faculty member in the Computer Science Department at Maharishi University of Management in Fairfield, Iowa. If he had any spare time, he would probably spend it hiking. Ellen Finkelstein is the author of numerous best-selling computer books on AutoCAD, PowerPoint, Flash, and most recently OpenOffice.org. She writes regular articles on AutoCAD and PowerPoint in magazines, e-zines, and for Web sites. She is an adjunct Instructor of Management, teaching e-business courses to M.B.A. students. She writes at home so that she can take the bread out of the oven on time. 01 559575 FM.qxd 3/2/04 3:53 PM Page v Dedication To MMY, for explaining the organizing power of Natural Law that sustains the existence and evolution of the entire universe and showing us how to make use of this power in our daily lives to achieve maximum results through minimum effort. Authors’ Acknowledgments Mike Robinson First and foremost I have to thank my co-author, Ellen Finkelstein, who initiated me into the ins and outs of writing a book. Ellen is the epitome of cool under the pressure of deadlines. She always manages to have a great sense of humor and shiny outlook regardless of the situation. Thanks for your patience. Thanks to my wife, Pat, who is always my guiding inspiration. Ellen Finkelstein I’d like to start out by thanking Mike Robinson for his extensive knowledge and experience, clear thinking, integrity, sense of responsibility, and great flexibility. Mike is the fountain of knowledge for this book. He is always a pleasure to work with. Thanks to my husband, Evan, and kids, Yeshayah and Eliyah (who want to see their names in a book), who support me while I’m writing, writing, and writing some more. Collectively At Wiley, our esteemed publisher, we’d like to thank Terri Varveris, our acqui sitions editor, for her ever-lively support. Both Linda Morris and Susan Pink were our able project editors, keeping track of innumerable details, including chapters, figures, and by how many pages we were over our quota. They kept us on track and made it easy. Thanks to Peter Just, our friend and colleague, who did a thorough and care ful job of technical editing, making sure that our terms and code were correct and that we were consistent and clear. He also contributed the material for Chapter 5. 01 559575 FM.qxd 3/2/04 3:53 PM Page vi Publisher’s Acknowledgments We’re proud of this book; please send us your comments through our online registration form located at www.dummies.com/register/. Some of the people who helped bring this book to market include the following: Acquisitions, Editorial, and Production Media Development Project Coordinator: Nancee Reeves Project Editors: Susan Pink and Linda Morris Layout and Graphics: Andrea Dahl, Acquisitions Editor: Terri Varveris Lauren Goddard, Denny Hager, Lynsey Osborn, Heather Ryan, Technical Editor: Peter Just Jacque Schneider Editorial Manager: Carol Sheehan Proofreaders: Andy Hollandbeck, Permissions Editor: Laura Moss Carl William Pierce, Media Development Manager: TECHBOOKS Production Services Laura VanWinkle Indexer: TECHBOOKS Production Services Media Development Supervisor: Richard Graves Editorial Assistant: Amanda Foxworth Cartoons: Rich Tennant (www.the5thwave.com) Publishing and Editorial for Technology Dummies Richard Swadley, Vice President and Executive Group Publisher Andy Cummings, Vice President and Publisher Mary C. Corder, Editorial Director Publishing for Consumer Dummies Diane Graves Steele, Vice President and Publisher Joyce Pepple, Acquisitions Director Composition Services Gerry Fahey, Vice President of Production Services Debbie Stailey, Director of Composition Services 01 559575 FM.qxd 3/2/04 3:53 PM Page vii Contents at a Glance Introduction .................................................................1 Part I: Getting to Know Jakarta Struts ..........................7 Chapter 1: Starting with the Basics .................................................................................9 Chapter 2: Laying the Groundwork ...............................................................................25 Chapter 3: Creating a Simple Web Application with Struts ........................................47 Part II: Starting from the Core ....................................89 Chapter 4: Controlling with the Controller ..................................................................91 Chapter 5: Creating the Model .....................................................................................109 Chapter 6: Designing the View .....................................................................................137 Chapter 7: Setting the Configuration ..........................................................................159 Part III: Expanding Your Development Options ...........189 Chapter 8: Exceptions to the Rule ...............................................................................191 Chapter 9: Getting Friendly with Plug-ins ...................................................................209 Chapter 10: Getting a Helping Hand with Tag Libraries ...........................................225 Chapter 11: Working with Page Composition Techniques .......................................249 Chapter 12: Securing Your Application ......................................................................265 Part IV: Putting It All Together .................................279 Chapter 13: Logging Your Actions ...............................................................................281 Chapter 14: Creating the MusicCollection.com Application ....................................287 Part V: The Part of Tens ...........................................327 Chapter 15: Ten Helpful Extensions to Struts ............................................................329 Chapter 16: Ten Ways to Find More Information .......................................................337 Part VI: Appendixes .................................................345 Appendix A: Struts-EL and JSTL Tag Library Syntax .................................................347 Appendix B: Glossary ...................................................................................................375 Index .......................................................................379 01 559575 FM.qxd 3/2/04 3:53 PM Page ix Table of Contents Introduction ..................................................................1 About This Book ..............................................................................................1 How to Use This Book ....................................................................................2 Foolish Assumptions ......................................................................................2 Conventions Used in This Book ....................................................................3 How This Book Is Organized ..........................................................................3 Part I: Getting to Know Jakarta Struts ...............................................4 Part II: Starting from the Core ..............................................................4 Part III: Expanding Your Development Options .................................4 Part IV: Putting It All Together .............................................................4 Part V: The Part of Tens ........................................................................4 Part VI: Appendixes ...............................................................................5 Icons Used in This Book .................................................................................5 Where to Go from Here ...................................................................................5 Part I: Getting to Know Jakarta Struts ...........................7 Chapter 1: Starting with the Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9 What Is Jakarta Struts? ...................................................................................9 Structuring a Web Application ....................................................................11 Using Java Servlets ..............................................................................12 Creating JavaServer Pages .................................................................13 Using JavaBeans ..................................................................................14 Understanding the Model-View-Controller Design Pattern .....................17 What is a design pattern? ...................................................................18 The MVC design pattern .....................................................................18 How Struts enforces the MVC pattern ..............................................19 Chapter 2: Laying the Groundwork . . . . . . . . . . . . . . . . . . . . . . . . . . . . .25 Getting Java ....................................................................................................26 Downloading and installing Java .......................................................26 Setting the Java Home environment variable ..................................28 Getting the Web Container ...........................................................................29 Downloading Tomcat to Windows ....................................................29 Installing Tomcat under Windows .....................................................29 Installing Tomcat under Linux or Mac OS X .....................................31 Starting and testing Tomcat ...............................................................32 01 559575 FM.qxd 3/2/04 3:53 PM Page x x Jakarta Struts For Dummies Choosing Your Development Environment ................................................33 Downloading and Installing Eclipse ............................................................34 Getting the Tomcat Launcher Plug-in for Eclipse .....................................35 Downloading and installing the Tomcat Launcher plug-in ............35 Configuring the Tomcat Launcher plug-in ........................................36 Getting Struts .................................................................................................39 Downloading Struts .............................................................................40 Reviewing the components of Struts ................................................41 Testing Your Web Application Development Environment .....................43 Chapter 3: Creating a Simple Web Application with Struts . . . . . . . .47 Designing Your First Struts Application .....................................................48 Application requirements ...................................................................48 Determining which components to use ............................................49 Putting Everything in Place .........................................................................49 Creating the project in Eclipse ..........................................................50 Setting up the application folders .....................................................52 Importing the Struts files ....................................................................54 Creating the JavaServer Pages ....................................................................59 The login.jsp page ...............................................................................59 The loggedin.jsp page .........................................................................64 Using message resources ...................................................................67 Making the Formbean ...................................................................................69 Adding a JavaBean ........................................................................................74 Creating an Action .........................................................................................75 Configuring Struts .........................................................................................78 Defining web.xml .................................................................................78 Configuring Struts with struts-config.xml ........................................81 Strutting Your Stuff: Running the Application ...........................................85 Deploying the Login application .......................................................85 Testing the application .......................................................................85 Debugging with Eclipse ......................................................................87 Part II: Starting from the Core .....................................89 Chapter 4: Controlling with the Controller . . . . . . . . . . . . . . . . . . . . . . .91 Understanding the Struts Controller Classes ............................................91 Working with the Master Controller — the ActionServlet .......................93 Starting the Servlet .............................................................................94 Processing requests ............................................................................97 Shutting down the Servlet ..................................................................97 Working with the Controller’s Helper — RequestProcessor ...................98 Getting Down to Work: Extending ActionClass .......................................100 Using the execute method ................................................................101 Predefined Action classes ................................................................103 Action Forms ......................................................................................108 01 559575 FM.qxd 3/2/04 3:53 PM Page xi xi Table of Contents Chapter 5: Creating the Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .109 Understanding the Model ..........................................................................109 Working with Business Objects .................................................................110 Meeting requirements for business objects ..................................111 Adding helper classes .......................................................................112 Using JavaBeans ................................................................................112 Implementing the Model ............................................................................112 Achieving persistence .......................................................................113 Getting MySQL .............................................................................................113 Downloading and installing MySQL ................................................114 Downloading MySQL Connector/J ..................................................114 Setting Up Your IDE and Web Container ..................................................115 Importing the class library into Eclipse .........................................115 Adding the class library to Tomcat .................................................116 Working with MySQL ..................................................................................117 Starting and stopping MySQL ..........................................................118 Creating a database ...........................................................................120 Creating a table in MySQL ................................................................121 Inserting data in the users table ......................................................121 Executing queries ..............................................................................122 Exiting the MySQL command tool ...................................................123 Connecting the Model to the Database ....................................................123 Working with JDBC ............................................................................124 Retrieving multiple records .............................................................126 Pooling Connections ...................................................................................130 Jakarta Commons DBCP ...................................................................131 Using connection pooling .................................................................132 Configuring the data source in Struts .............................................134 Chapter 6: Designing the View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .137 Choosing JSP or an Alternative .................................................................137 Template engines ...............................................................................137 XML tools ...........................................................................................139 Internationalization .....................................................................................139 Creating multinational applications ................................................140 Using one source for String type constants ...................................148 Mediating between the View and the Controller ....................................149 Configuring the formbean ................................................................150 Interactions with the formbean .......................................................151 Preparing the form with the reset method ....................................152 Indexing data ......................................................................................152 Validating data ...................................................................................152 Declarative form validation ..............................................................154 Notifying Users of Problems ......................................................................154 Mediating Automatically ............................................................................155 Configuring the DynaActionForm class ..........................................156 Differences between ActionForm and DynaActionForm ..............157 01 559575 FM.qxd 3/2/04 3:53 PM Page xii xii Jakarta Struts For Dummies Chapter 7: Setting the Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . .159 Stringing the Parts Together ......................................................................159 Editing the Web Container Configuration File .........................................160 The ServletContext configuration tag .............................................162 Listener configuration ......................................................................163 ActionServlet configuration .............................................................163 ActionServlet mapping .....................................................................166 Adding in the tag libraries ................................................................166 A complete example of a web.xml file ............................................167 Modifying the Struts Configuration File ...................................................169 DataSource configuration .................................................................169 Formbean configuration ...................................................................171 Global exceptions ..............................................................................174 Global forwards .................................................................................175 Action mapping .................................................................................176 Controller configuration ...................................................................179 Message resource configuration .....................................................181 Plug-in configuration .........................................................................183 Complete example of a struts-config.xml file .................................184 Part III: Expanding Your Development Options ............189 Chapter 8: Exceptions to the Rule . . . . . . . . . . . . . . . . . . . . . . . . . . . . .191 Java Errors and Exceptions .......................................................................192 Try/catch block .................................................................................192 Throwing exceptions ........................................................................193 Wrapping it up in finally ...................................................................194 Exception Strategies ...................................................................................196 Catching exceptions ..........................................................................196 Exception information ......................................................................196 Writing Your Own Exception Classes .......................................................197 Using Chained Exceptions .........................................................................198 Asserting Yourself .......................................................................................199 Handling Exceptions Yourself ....................................................................201 Saving information ............................................................................202 Recovering from errors ....................................................................202 Inform the user ..................................................................................202 Fail gracefully .....................................................................................202 Declarative Exception Handling ................................................................203 Declaring the exception ....................................................................204 Global or local exception handling .................................................204 Extending ExceptionHandler .....................................................................205 Handling RuntimeExceptions in Struts ....................................................207