Вы находитесь на странице: 1из 15

Beginning JavaServer Pages

Vivek Chopra
Sing Li
Rupert Jones
Jon Eaves
John T. Bell
Beginning JavaServer Pages
Beginning JavaServer Pages

Vivek Chopra
Sing Li
Rupert Jones
Jon Eaves
John T. Bell
Beginning JavaServer Pages
Published by
Wiley Publishing, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com
Copyright 2005 by Wiley Publishing, Inc., Indianapolis, Indiana
Published by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 0-7645-7485-X
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
1B/QT/QS/QV/IN
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-4355, e-mail: brandreview@wiley.com.

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 CON-
TENTS 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 INFOR-
MATION 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 Cus-
tomer 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 Cataloging-in-Publication Data
Beginning JavaServer pages / Vivek Chopra ... [et al.].
p. cm.
Includes index.
ISBN 0-7645-7485-X (paper/website)
1. JavaServer pages. 2. Web sites--Design. 3. Web site development. I. Chopra, Vivek.
TK5105.8885.J38B45 2005
006.7 6--dc22
2004024591
Trademarks: Wiley, the Wiley Publishing logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade
dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States
and other countries, and may not be used without written permission. JavaServer Pages is a trademark of Sun
Microsystems, Inc. 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.
About the Authors
Vivek Chopra has over ten years of experience as a software developer, architect, and team lead, with
extensive experience with Web services, J2EE, and middleware technologies. He has worked and con-
sulted at a number of Silicon Valley companies and startups and has (pending) patents on Web services.
Vivek actively writes about technology and has coauthored half a dozen books on topics such as open-
source software, Java, XML, and Web services. He contributes to open source, too, and has developed
parts of the uddi4j library, an open-source Java API for UDDI.

Sing Li, first bit by the microcomputer bug in 1978, has grown up with the microprocessor age. His first
personal computer was a do-it-yourself Netronics COSMIC ELF computer with 256 bytes of memory,
mail-ordered from the back pages of Popular Electronics magazine. Currently, Sing is a consultant, system
designer, open-source software contributor, and freelance writer. He writes for several popular technical
journals and e-zines and is the creator of the Internet Global Phone, one of the very first Internet phones
available. He has authored and coauthored numerous books across diverse technical topics, including
JSP, Tomcat, servlets, XML, Jini, and JXTA.

Rupert Jones is a Technical Lead for J2EE projects at Internet Business Systems. Over the past six years,
Rupert has provided software development and consulting services for blue-chip companies, both in
Australia and internationally. He lives and works in Melbourne, Australia. Rupert can be contacted at
rup@rupertjones.com.

Jon Eaves has been developing software in a variety of languages and domains for over 15 years. He is
currently employed by ThoughtWorks, developing large-scale enterprise systems using J2EE. When he
can find spare time, he develops J2ME/MIDP applications and works on the BouncyCastle Crypto APIs
(www.bouncycastle.org). Jon can be reached at jon@eaves.org.

John T. Bell has more than 20 years of software development experience and currently serves as the lead
software architect for the Web site of a major hospitality company based in Bethesda, Maryland. He is
also an adjunct professor, teaching server-side Java technologies for the Center for Applied Information
Technology at Towson State University. He has a masters degree in Computer Systems Management
and a bachelors degree in Electrical Engineering, both from the University of Maryland. This is Mr.
Bells third contribution to a Wrox title. He is also the author of The J2EE Open Source Toolkit.
Credits
Acquisitions Editor Project Coordinator
Robert Elliott April Farling

Development Editor Graphics and Production Specialists


Sydney Jones Jonelle Burns
Carrie A. Foster
Technical Editor Lauren Goddard
Wiley-Dreamtech India Pvt Ltd Denny Hager
Joyce Haughey
Production Editor Amanda Spagnuolo
William A. Barton
Quality Control Technicians
Copy Editor Jessica Kramer
Luann Rouff Susan Moritz
Carl William Pierce
Editorial Manager Charles Spencer
Mary Beth Wakefield
Media Development Specialist
Vice President and Executive Group Publisher Kit Malone
Richard Swadley
Proofreading and Indexing
Vice President and Publisher TECHBOOKS Production Services
Joseph B. Wikert
Acknowledgments
Vivek Chopra
Id like to thank my coauthors and all the folks at Wrox for the effort and the long hoursthank you,
Rupert, Sing, Jon, John, Sydney, James, and Bob! Id especially like to thank my wife, Rebecca, for her
patience and support, especially since I spent most weekends working on this book.

Sing Li
Thanks to the virtual Beginning JavaServer Pages team, top professionals from all corners of the globe.
It was wonderful working with you throughout 2003 and 2004.

To my wife, Kimyour inspiration and support are the high-octane fuel that keeps me running, looking
joyfully forward to each brave new day.

Rupert Jones
First of all, Id like to thank my coauthors for their dedication to this book. Its not easy holding down a
full-time job in this industry and fitting in time for such a venture. I am constantly amazed we all still
have friends and family who will talk to us, let alone recognize us. Its been a pleasure undertaking this
task with a group of such consummate professionals.

To the Wrox crewin particular, Sydney Jones, our developmental editor, and our tech reviewers at
DreamTechthanks for all your hard work in getting us across the line. I know its difficult working
with technical people at the best of times, especially when they are geographically remote.

Thanks also to my colleagues at Internet Business Systems: Steve Hayes, Rob Mitchell, and Shane
Clauson. These guys provided me with much-needed help, advice, and encouragement, even in my
grumpier moments. It really is a pleasure to work with each of you.

And last but certainly not least, thanks to my loving family: Julia, Michael, Nick, and Caroline.

Jon Eaves
Id like to thank my coauthors and the team at Wrox for the hard work they put in while creating this
book. Closer to home, Id like to thank my family for their encouragement, patience, and support. Mum
and Dad, everything I can do is because of your love. My wonderful wife, Sue, you rock my world more
and more every day. Boo and Maddy, your purring late at night kept me going when the words
wouldnt come. Thank you, all.

John T. Bell
To Tammy, my loving and patient wife, maybe someday I will write a book that you can read, and to my
grandmother, Valmai Locklair, who slipped away from us as I was writing my chapters.
Contents

About the Authors v


Acknowledgments vii

Introduction xxv
The Right Way to Do Web Development xxv
Approach xxvi
How This Book Is Structured xxvi
Conventions xxix
Source Code xxx
Errata xxx
p2p.wrox.com xxx

Part I: JSP Fundamentals 1

Chapter 1: Getting Started with JavaServer Pages 3


Creating Applications for the Internet 4
Limitations of the basic Web server model 5
Dynamic HTML generation via CGI 5
Shortcomings of CGI 7
Improving Java-based CGI: servlets 7
Summary 28
Exercises 29

Chapter 2: JSP Basics 1: Dynamic Page Creation for Data Presentation 31


The Anatomy of a JSP Page 31
Directives 32
XML-compatible syntax 33
Template data 33
Action 34
Scripting elements 35
Handling HTML form submission with JSP 36
Web site personalization 60
Summary 70
Exercises 71
Contents
Chapter 3: JSP Basics 2: Generalized Templating and Server Scripting 73
Scripting Elements for Java Code Embedding 74
Scripting elements 75
Creating a Simple Web Storefront 80
Attaching attributes to implicit objects 86
Rendering the list of categories 88
Rendering the list of products in a given category 89
Adding a Shopping Cart to a Catalog 90
Creating the Shopping Cart 95
Decoding incoming request parameters 97
Rendering order information 98
Rendering the Return to Shopping hyperlink 98
Shopping cart limitations 99
Overcoming the shopping cart limitations 100
Sessions and JSPs 107
Rendering the shopping cart using a session attribute 111
Summary 114
Exercises 115

Chapter 4: CSS, JavaScript, VBScript, and JSP 117


Code Elements That Execute
on the Client Side 118
Cascading Stylesheets 119
JavaScript 120
VBScript 121
User Preference Implementation 121
Creating a User-Customizable DHTML Menu 132
Summary 143
Exercises 144

Chapter 5: JSP and EL 145


EL and Its Vital Role in JSP 146
EL Named Variables 146
Applying EL 148
Using EL expressions inline with template data 148
Using EL expressions in attribute values 148
Coercion: Automatic Type Conversion 157
Boxing and unboxing 157
Coercion to a string 157
Coercion to a number 158

x
Contents
Coercion to a character 158
Best attempt to do the right thing without error 158
Accessing Object Properties and Collections 162
Implicit EL Objects in JSP 2.0 167
User-Supplied Functions within EL 173
Namespace and EL functions 173
Static methods of a Java class 173
Summary 177
Exercises 178

Chapter 6: JSP Tag Libraries and JSTL 179


The Vital Role of JSP Tag Libraries 180
The JSP Standard Tag Library 181
Anatomy of a Tag Library 182
The Tag Library Descriptor 182
The taglib map in the web.xml deployment descriptor 183
Locating JSTL and understanding tag library packaging 184
JSTL tags 184
Summary 210
Exercises 211

Chapter 7: JSP Directives 213


Directive Basics 214
Directives as instructions for the container 214
Alternative XML syntax for directives 214
Available JSP directives 215
The page Directive 217
The language attribute 217
The extends attribute 217
The import attribute 218
The session attribute 218
The info attribute 219
The isELIgnored attribute 219
The isErrorPage attribute 219
The errorPage attribute 220
The contentType attribute 220
The taglib Directive 223
Two general usage forms for the taglib directive 224
Attributes of the taglib directive 225
How It Works 227

xi
Contents
The include Directive 231
The include performed at translation time 231
Summary 239
Exercises 239

Chapter 8: JSP Standard Actions 241


JSP Standard Actions Are Built-in Tags 242
Actions for Working with JavaBeans 242
The <jsp:useBean> standard action 243
How <jsp:useBean> and JSTL <c:set> Differ 258
Including JSP Output via <jsp:include> 259
Transferring Control Between JSPs 264
The <jsp:forward> standard action 264
Specifying Parameters for Other Actions 265
The <jsp:param> standard action 265
Working with Plug-ins 266
The <jsp:plugin> standard action 267
The <jsp:params> standard action 267
The <jsp:fallback> standard action 268
Standard Actions Specific to Tag Files 273
Summary 274
Exercises 274

Chapter 9: JSP and JavaBeans 275


Anatomy of a JavaBean 276
JavaBean Properties 277
JavaBean methods 280
Common JavaBean packaging 281
How JavaBeans and EJBs Differ 301
Summary 301
Exercises 302

Chapter 10: Error Handling 303


Understanding the Origin of Errors 303
Errors in Java language coding 304
Errors in JSP directives and actions 309
JSTL errors and EL errors 326
User data-input errors 327
Errors found in JSP template data 327

xii
Contents
Summary 328
Exercises 328

Chapter 11: Building Your Own Custom JSP Tag Library 329
What Is a Tag File? 329
A Simple Tag File: Displaying Todays Date 330
Advantages of Tag Files 331
Code reuse 331
Hiding complexity 331
Separation of concerns 331
Simplicity 332
Flexible packaging 332
Developing Tag Files 332
Scope and implicit objects 332
Using directives in tag files 335
Body processing 341
Attributes 345
Packaging Tag Files 355
Java custom actions versus tag file custom actions 358
Summary 359
Exercises 359

Chapter 12: Advanced Dynamic Web Content Generation 361


Data Validation in Web Applications 362
Server-side validation and efficient usage of resources 363
Client-side data validation 364
The need for server-side validation 365
Common client-side validation scenarios 365
Operation of client-side validation 365
Dynamic generation of client-side JavaScript code 379
Dynamic generation of XML using JSP 386
Summary 392
Exercises 393

Chapter 13: Internationalization and Localized Content 395


About Internationalization-Ready Applications 396
Internationalization and Localization 396
The unique i18n requirements of a Web-based JSP application 397

xiii

Вам также может понравиться