100% found this document useful (12 votes)
46 views

Instant Download Beginning JavaServer Pages 1st Edition Vivek Chopra PDF All Chapters

Beginning

Uploaded by

mamboboffo6y
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (12 votes)
46 views

Instant Download Beginning JavaServer Pages 1st Edition Vivek Chopra PDF All Chapters

Beginning

Uploaded by

mamboboffo6y
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Download the full version of the ebook at ebookname.

com

Beginning JavaServer Pages 1st Edition Vivek


Chopra

https://ebookname.com/product/beginning-javaserver-
pages-1st-edition-vivek-chopra/

OR CLICK BUTTON

DOWNLOAD EBOOK

Download more ebook instantly today at https://ebookname.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

JavaServer Pages Fast Easy Web Development w CD 1st


Edition Aneesha Bakharia

https://ebookname.com/product/javaserver-pages-fast-easy-web-
development-w-cd-1st-edition-aneesha-bakharia/

ebookname.com

Sams Teach Yourself JavaServer Pages in 21 Days 1st


Edition Steven Holzner

https://ebookname.com/product/sams-teach-yourself-javaserver-pages-
in-21-days-1st-edition-steven-holzner/

ebookname.com

Freedom from Addiction The Chopra Center Method for


Overcoming Destructive Habits Deepak Chopra

https://ebookname.com/product/freedom-from-addiction-the-chopra-
center-method-for-overcoming-destructive-habits-deepak-chopra/

ebookname.com

Options for the Beginner and Beyond Unlock the


Opportunities and Minimize the Risks 1st Edition W. Edward
Olmstead
https://ebookname.com/product/options-for-the-beginner-and-beyond-
unlock-the-opportunities-and-minimize-the-risks-1st-edition-w-edward-
olmstead/
ebookname.com
Dictionary of Computing Over 10 000 terms clearly defined
5th Edition Paul Roseby

https://ebookname.com/product/dictionary-of-computing-
over-10-000-terms-clearly-defined-5th-edition-paul-roseby/

ebookname.com

Handbook of Research on Effective Electronic Gaming in


Education Set of 3 1st Edition Richard E. Ferdig

https://ebookname.com/product/handbook-of-research-on-effective-
electronic-gaming-in-education-set-of-3-1st-edition-richard-e-ferdig/

ebookname.com

Introduction to Pragmatics 1st Edition Betty J. Birner

https://ebookname.com/product/introduction-to-pragmatics-1st-edition-
betty-j-birner/

ebookname.com

Diagnostic Imaging Brain 1st Edition Anne Osborn

https://ebookname.com/product/diagnostic-imaging-brain-1st-edition-
anne-osborn/

ebookname.com

Mobile Radio Channels 2nd Edition Matthias Patzold

https://ebookname.com/product/mobile-radio-channels-2nd-edition-
matthias-patzold/

ebookname.com
Encyclopedia of Jewish American Literature Encyclopedia of
American Ethnic Literature 1st Edition Gloria L. Cronin

https://ebookname.com/product/encyclopedia-of-jewish-american-
literature-encyclopedia-of-american-ethnic-literature-1st-edition-
gloria-l-cronin/
ebookname.com
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 master’s degree in Computer Systems Management
and a bachelor’s degree in Electrical Engineering, both from the University of Maryland. This is Mr.
Bell’s 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
I’d like to thank my coauthors and all the folks at Wrox for the effort and the long hours—thank you,
Rupert, Sing, Jon, John, Sydney, James, and Bob! I’d 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, Kim—your 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, I’d like to thank my coauthors for their dedication to this book. It’s 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. It’s been a pleasure undertaking this
task with a group of such consummate professionals.

To the Wrox crew—in particular, Sydney Jones, our developmental editor, and our tech reviewers at
DreamTech—thanks 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
I’d like to thank my coauthors and the team at Wrox for the hard work they put in while creating this
book. Closer to home, I’d 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
wouldn’t 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 Today’s 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
Contents
Building on the Java Platform’s i18n Capabilities 399
The concept of a locale 399
Maintaining locale information 400
Summary 433
Exercises 434

Chapter 14: JSP Debugging Techniques 435


The Science of Debugging 436
Catching Bugs at Compile Time 437
Using a Debugging System versus a Production System 441
Using System.out.println() to Instrument Code 442
Using a Logging System 445
Logging through the servlet container 445
Logging with the JDK logger 447
Logging with Log4j 454
Logging with tag libraries 460
Debugging with Tools 464
Setting breakpoints 464
Examining variables and setting watchpoints 467
Stepping through code 468
Remote debugging 468
Debugging Code in Production Environments 469
Debugging when the JSP is precompiled 470
Debugging under load 470
Adding contextual information to log files 471
Adding log filters 474
Finding the Intermittent Problem 474
Adding information as response comments 474
Snoop application 475
Avoiding Concurrency Issues 479
Summary 479
Exercises 479

Part II: JSP and Modern Web Server


Software Development 481

Chapter 15: JSPs and Servlets 483


A JSP Is a Servlet 484
Anatomy of a servlet 488
The lifecycle of a servlet 492

xiv
Contents
Describing servlets to containers in the deployment descriptor 495
The servlet declaration 497
Using servlets when JSP is available 503
Specifying initialization parameters 504
Accessing initialization parameters within the ControllerServlet 506
Custom forwarding of incoming requests via the controller servlet 508
The forwarding targets 509
Summary 510
Exercises 510

Chapter 16: The Role of JSP in the Wider Context: Web Applications 511
What Is a Web Application? 512
Directory Structure for a Web Application 512
The Deployment Descriptor 513
Deployment descriptor elements for a JSP developer 513
Using a Web Archive 523
Development and Deployment Strategies 523
Packaging and Deploying for Tomcat 524
Introduction to Web application security 528
Summary 529
Exercises 530

Chapter 17: Model View Controller 533


What Is MVC? 534
MVC and Web Applications 534
Summary 546
Exercise 547

Chapter 18: Web Frameworks 549


What Is a Framework? 549
Why Frameworks Are Good 550
Types of Frameworks 551
Application frameworks 551
Persistence frameworks 552
Utility frameworks 553
WebWork 554
Components of WebWork 554

xv
Contents
The Spring Framework 567
Main components of the Spring MVC 567
An example using Spring 569
Summary 589
Exercises 590

Chapter 19: Struts Framework 591


Introducing Struts 592
A Struts walkthrough 593
Controller: actions and forms 594
Model 603
View 604
Example application 624
Summary 641
Exercises 641

Chapter 20: Layout Management with Tiles 643


Introduction to Tiles 643
What is the Tiles framework? 644
Tiles terminology 645
Installing Tiles 646
Tile Scope 650
Definitions 650
Tiles Tags 652
insert 653
definition 654
put 654
putList 655
add 656
get 656
getAsString 656
useAttribute 657
importAttribute 657
initComponentDefinitions 658
Passing Parameters to Tiles 658
Advanced Tiles 659
Definitions and inheritance 659
Nesting tiles 664

xvi
Contents
Tiles and Struts 671
Configuring Tiles with Struts 671
Tiles definitions as action forwards 671
Passing values from Struts to Tiles 673
Summary 678
Exercises 679

Chapter 21: JavaServer Faces 681


Configuring a JSF Project 681
Getting Started with JSF 683
Using backing beans 685
Managed beans 687
Controlling navigation 687
Preventing direct access to Faces JSP files 690
JSF Lifecycle 690
Restore view 692
Apply request values 692
Process validations 692
Update model values 692
Invoke application 693
Render response 693
Validating Data 693
Using standard validators 697
Creating your own validation 697
Converting Data 705
Standard converters 711
Implementing the Converter interface 713
Handling Events with Listeners 715
JSF versus Struts 718
Summary 719
Exercises 719

Chapter 22: JSP in J2EE 721


Overview of J2EE 721
What is J2EE? 722
What does a container do? 724
J2EE Technologies 724
J2EE APIs 725
J2EE platform architecture 727
JSP development scenarios 728

xvii
Contents
Using JSP with J2EE Components 729
Servlets 730
JNDI 735
JDBC 738
EJB 741
Benefits of EJB 742
Restrictions on EJB 742
Types of EJB 743
Session beans 743
Entity beans 744
Message-driven beans 745
Timer Service 745
Summary 746
Exercises 746

Chapter 23: Access to Databases 747


Introduction to Databases 748
Connecting to a database 749
Downloading and Installing MySQL 752
JDBC APIs 753
Building Applications 774
Data characteristics 774
Transactions 775
Object-relational mapping 777
Different Types of Applications 777
Simple applications 778
Using JSP and JDBC 778
More complex applications 782
Using Hibernate 782
Installing Hibernate 784
Summary 823

Chapter 24: Security 825


Areas of Security 825
Authentication 826
Authorization 828
Data integrity 830
Confidentiality 830
Data Integrity and Confidentiality 830
Implementing SSL 831

xviii
Contents
Authentication 837
HTTP BASIC authentication 837
Form-based authentication 843
Client-certificate authentication 849
Authorization 855
Container 855
Programmatic 855
Summary 860
Exercises 860

Chapter 25: Performance 861


Performance Concepts 861
What to measure 862
The user’s perspective 863
How to measure performance 863
What to do after performance testing 865
Measuring Performance Using JMeter 866
Installing JMeter 866
JMeter concepts 866
Performance Tuning Tips 872
Development-time measures 872
Deployment-time measures 875
Summary 883

Chapter 26: Best Practices and Tools 885


Development Methodologies 886
Waterfall and iterative methodologies 886
Rational Unified Process 888
Extreme Programming 888
Test-driven development 889
Feature-driven development 890
Development Tools 890
Version-control tools 890
Build tools 890
Testing tools 891
Logging tools 891
Tools for enforcing coding standards 891
Apache Ant 892
Installing Ant 892
Ant concepts 893
Additional resources 903

xix
Contents
CVS 903
Installing CVS 903
CVS concepts 903
Connecting to a CVS server 904
Checking in code 905
Checking out code 906
Comparing changes across revisions 906
Additional resources 907
JUnit 907
Installing JUnit 907
JUnit concepts 908
Additional resources 915
HttpUnit 915
Installing HttpUnit 915
HttpUnit concepts 916
Additional resources 919
Best Practices for Web Development 919
Follow good JSP coding practices 919
Separate application logic and presentation 920
Use design patterns where appropriate 920
Use frameworks for developing applications 921
Early testing and integration 921
Summary 921
Exercises 922

Part III: Spreading Your New Wings:


Applying JSP in the Real World 923

Chapter 27: JSP Project I: Personalized Portal 925


The Portal Project 925
Introduction to RSS 926
Introduction to Web services 929
Project Features 930
Use cases 931
Initial analysis 931
The Application Design 932
Designing the persistent store 932
Defining the key entity objects 935
Designing the Web site control flow 944

xx
Contents
The Development Environment 945
Directory structure 946
Build scripts 947
Struts 949
Tiles 950
Log4j 951
Rome 953
Apache Axis 956
The Application 958
View 959
Controller 966
Running the portal application 975
Summary 981
Exercises 981

Chapter 28: JSP Project II: Shopping Cart Application 983


The Bookstore Project 984
Project features 984
Use cases 984
Initial analysis 985
Application Design 986
Database design 986
Defining the key entity objects 989
The Development Environment and Its Configuration 1008
Directory structure 1009
Tomcat 1010
Ant 1010
Database 1016
Hibernate 1016
Struts, Validator, and Tiles 1022
web.xml 1023
The Application 1024
Application layout: Tiles 1024
Cart status 1026
Presenting a list of categories 1028
Presenting a list of books 1030
Adding a book to the shopping cart 1034
Managing the shopping cart 1036
Checkout 1042
Summary 1055
Exercises 1055

xxi
Contents

Part IV: Appendixes 1057

Appendix A: JSP Syntax Reference 1059


Scoping 1060
page scope 1060
request scope 1061
session scope 1061
application scope 1061
Implicit Objects 1062
The request object 1062
The response object 1062
The pageContext object 1063
The session object 1063
The application object 1064
The out object 1064
The config object 1065
The page object 1065
The exception object 1065
Directives 1066
The page directive 1066
The taglib directive 1067
The include directive 1067
Tag file directives 1068
Actions 1070
Standard actions 1070
Other JSP standard actions 1074
Scripting Elements 1075
Declaration scripting elements 1075
Scriptlets 1075
Expression scripting elements 1076

Appendix B: JSP Expression Language Reference 1077


EL Expressions 1077
EL expressions in-line with template data 1077
EL expressions in attribute values 1078
Accessing Arrays, Maps, Object Properties, and Collections 1078
Object properties access 1078
Array member access 1078
Java map access 1078
Java collection access 1079

xxii
Random documents with unrelated
content Scribd suggests to you:
After taking off his hat, and making a low bow,
Nibbles said:

“I think I have found your lordship’s ring, which


you lost. I have it around my neck.”

The Prince lifted Nibbles up, and looked at the


ring.

“That is most surely my Lucky Ring,” said he.


“Where did you find it?”

“In the sand at the bottom of the river,” answered


Nibbles, and he told the Prince how nearly drowned
he had been, and about Mr. Scratchetty-Claw.

“My old friend, the Alligator,” laughed the Prince.


“Oh, I know him well, the lazy scamp, for he eats up
all my best trout.”

Then he took the ring carefully from Nibbles’s


neck, and put it on his own finger.

“You have given me back what I prize most in the


world,” he said, “and your reward shall be in
proportion. Every year, as long as you live, you shall
receive a bag of gold.”

Nibbles was almost too happy to speak, but he


thanked the Prince and kissed his hand. A page was
sent to bring the gold, and a few minutes later,
Nibbles and Teenie Weenie, carrying the precious
bag between them, were hurrying back to the raft.

They found Mr. Scratchetty-Claw fast asleep, but


Nibbles, dancing with joy, woke him up to hear the
great news.

“Good enough!” said the Alligator. “It’s a lucky


thing for you that I tipped you into the river.”

“It certainly was,” said Nibbles, “for now my


mother will never have to work any more. Let us
hurry home to her as fast as we can, Teenie Weenie.”

“I’ll take you part of the way,” yawned Mr.


Scratchetty-Claw, “although I am fearfully sleepy.”
Chapter VIII

Nibbles’ Return

Away they sailed towards home, as happy as two


little mice could be.

Mr. Scratchetty-Claw towed them for a long way,


until he became so sleepy that he had to stop and
take a nap. He shed tears when he said good-bye to
Nibbles and Teenie Weenie, but he soon settled
himself comfortably on a mud bank in a shady spot,
and in two minutes was snoring so loudly that you
could have heard him half a mile away.

Nibbles and Teenie hoisted their sail, and, as they


floated along, Teenie Weenie sang this song:

“Two little mice sailed down the stream


One lovely summer day.
The sky was blue, the banks were green,
The birds in the tree tops sang unseen,
As they merrily sailed away.

“Their silken flag was red and white,


Their sail a butterfly’s wing;
With a firefly their pilot light,
They went to seek their fortune bright,
And found it in a ring.

“Deep buried in the golden sand,


Beneath the water blue,
Far away in a distant land
The little mice went hand in hand,
And sought the token true.”

For more than a week they sailed up the pretty


river, but at last, one afternoon at sunset, they
reached home. Quietly they stole up to the cottage
and peeped in at the window.
There was Mrs. Poppelty-Poppett cooking supper,
while Sniffy and Snuffy were peeling potatoes, and
Gobble was eating an apple behind the door.
Nibbles tapped gently on the window-pane, and
Mrs. Poppelty-Poppett turned quickly around. With a
squeak of perfect delight, she cried: “Oh, here is
Nibbles!” and ran to the door, upsetting the soup-
kettle right into the fire in her haste. Of course, Sniffy
and Snuffy, Gobble and the baby, all ran out, too, and
then they all talked together so fast that no one knew
what any one else was saying. Pretty soon they
quieted down, and Nibbles told them of his wonderful
adventures, and of the finding of the Lucky Ring.
When he gave his mother the bag of gold, poor little
Mrs. Poppelty-Poppett did not know whether to laugh
or cry with happiness, so she did both. She had
worked hard for her children, and now there would be
comfort and plenty for the rest of her life.

After a little while she dried her eyes, and thought


of supper. It was all in the fire and burned up!
“Never mind,” said Nibbles. “Teenie Weenie and I
would far rather have some of your nice corn cake
and toasted cheese than soup.”

“Indeed we would,” said Teenie Weenie.

So they all helped, and in a few minutes


everything was ready; and how good the supper
tasted!
When at last they went to bed, they all dreamed of
bags of Lucky Rings, and rivers of gold, guarded by
Alligators, who ate nothing but toasted cheese and
corn bread.
*** END OF THE PROJECT GUTENBERG EBOOK NIBBLES
POPPELTY-POPPETT ***

Updated editions will replace the previous one—the old editions


will be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States copyright
in these works, so the Foundation (and you!) can copy and
distribute it in the United States without permission and without
paying copyright royalties. Special rules, set forth in the General
Terms of Use part of this license, apply to copying and
distributing Project Gutenberg™ electronic works to protect the
PROJECT GUTENBERG™ concept and trademark. Project
Gutenberg is a registered trademark, and may not be used if
you charge for an eBook, except by following the terms of the
trademark license, including paying royalties for use of the
Project Gutenberg trademark. If you do not charge anything for
copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such
as creation of derivative works, reports, performances and
research. Project Gutenberg eBooks may be modified and
printed and given away—you may do practically ANYTHING in
the United States with eBooks not protected by U.S. copyright
law. Redistribution is subject to the trademark license, especially
commercial redistribution.

START: FULL LICENSE


THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK

To protect the Project Gutenberg™ mission of promoting the


free distribution of electronic works, by using or distributing this
work (or any other work associated in any way with the phrase
“Project Gutenberg”), you agree to comply with all the terms of
the Full Project Gutenberg™ License available with this file or
online at www.gutenberg.org/license.

Section 1. General Terms of Use and


Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand,
agree to and accept all the terms of this license and intellectual
property (trademark/copyright) agreement. If you do not agree to
abide by all the terms of this agreement, you must cease using
and return or destroy all copies of Project Gutenberg™
electronic works in your possession. If you paid a fee for
obtaining a copy of or access to a Project Gutenberg™
electronic work and you do not agree to be bound by the terms
of this agreement, you may obtain a refund from the person or
entity to whom you paid the fee as set forth in paragraph 1.E.8.

1.B. “Project Gutenberg” is a registered trademark. It may only


be used on or associated in any way with an electronic work by
people who agree to be bound by the terms of this agreement.
There are a few things that you can do with most Project
Gutenberg™ electronic works even without complying with the
full terms of this agreement. See paragraph 1.C below. There
are a lot of things you can do with Project Gutenberg™
electronic works if you follow the terms of this agreement and
help preserve free future access to Project Gutenberg™
electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright
law in the United States and you are located in the United
States, we do not claim a right to prevent you from copying,
distributing, performing, displaying or creating derivative works
based on the work as long as all references to Project
Gutenberg are removed. Of course, we hope that you will
support the Project Gutenberg™ mission of promoting free
access to electronic works by freely sharing Project
Gutenberg™ works in compliance with the terms of this
agreement for keeping the Project Gutenberg™ name
associated with the work. You can easily comply with the terms
of this agreement by keeping this work in the same format with
its attached full Project Gutenberg™ License when you share it
without charge with others.

1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside
the United States, check the laws of your country in addition to
the terms of this agreement before downloading, copying,
displaying, performing, distributing or creating derivative works
based on this work or any other Project Gutenberg™ work. The
Foundation makes no representations concerning the copyright
status of any work in any country other than the United States.

1.E. Unless you have removed all references to Project


Gutenberg:

1.E.1. The following sentence, with active links to, or other


immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project
Gutenberg™ work (any work on which the phrase “Project
Gutenberg” appears, or with which the phrase “Project
Gutenberg” is associated) is accessed, displayed, performed,
viewed, copied or distributed:

This eBook is for the use of anyone anywhere in the United


States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it
away or re-use it under the terms of the Project Gutenberg
License included with this eBook or online at
www.gutenberg.org. If you are not located in the United
States, you will have to check the laws of the country where
you are located before using this eBook.

1.E.2. If an individual Project Gutenberg™ electronic work is


derived from texts not protected by U.S. copyright law (does not
contain a notice indicating that it is posted with permission of the
copyright holder), the work can be copied and distributed to
anyone in the United States without paying any fees or charges.
If you are redistributing or providing access to a work with the
phrase “Project Gutenberg” associated with or appearing on the
work, you must comply either with the requirements of
paragraphs 1.E.1 through 1.E.7 or obtain permission for the use
of the work and the Project Gutenberg™ trademark as set forth
in paragraphs 1.E.8 or 1.E.9.

1.E.3. If an individual Project Gutenberg™ electronic work is


posted with the permission of the copyright holder, your use and
distribution must comply with both paragraphs 1.E.1 through
1.E.7 and any additional terms imposed by the copyright holder.
Additional terms will be linked to the Project Gutenberg™
License for all works posted with the permission of the copyright
holder found at the beginning of this work.

1.E.4. Do not unlink or detach or remove the full Project


Gutenberg™ License terms from this work, or any files
containing a part of this work or any other work associated with
Project Gutenberg™.
1.E.5. Do not copy, display, perform, distribute or redistribute
this electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
with active links or immediate access to the full terms of the
Project Gutenberg™ License.

1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if
you provide access to or distribute copies of a Project
Gutenberg™ work in a format other than “Plain Vanilla ASCII” or
other format used in the official version posted on the official
Project Gutenberg™ website (www.gutenberg.org), you must, at
no additional cost, fee or expense to the user, provide a copy, a
means of exporting a copy, or a means of obtaining a copy upon
request, of the work in its original “Plain Vanilla ASCII” or other
form. Any alternate format must include the full Project
Gutenberg™ License as specified in paragraph 1.E.1.

1.E.7. Do not charge a fee for access to, viewing, displaying,


performing, copying or distributing any Project Gutenberg™
works unless you comply with paragraph 1.E.8 or 1.E.9.

1.E.8. You may charge a reasonable fee for copies of or


providing access to or distributing Project Gutenberg™
electronic works provided that:

• You pay a royalty fee of 20% of the gross profits you derive from
the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”

• You provide a full refund of any money paid by a user who


notifies you in writing (or by e-mail) within 30 days of receipt that
s/he does not agree to the terms of the full Project Gutenberg™
License. You must require such a user to return or destroy all
copies of the works possessed in a physical medium and
discontinue all use of and all access to other copies of Project
Gutenberg™ works.

• You provide, in accordance with paragraph 1.F.3, a full refund of


any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.

• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.

1.E.9. If you wish to charge a fee or distribute a Project


Gutenberg™ electronic work or group of works on different
terms than are set forth in this agreement, you must obtain
permission in writing from the Project Gutenberg Literary
Archive Foundation, the manager of the Project Gutenberg™
trademark. Contact the Foundation as set forth in Section 3
below.

1.F.

1.F.1. Project Gutenberg volunteers and employees expend


considerable effort to identify, do copyright research on,
transcribe and proofread works not protected by U.S. copyright
law in creating the Project Gutenberg™ collection. Despite
these efforts, Project Gutenberg™ electronic works, and the
medium on which they may be stored, may contain “Defects,”
such as, but not limited to, incomplete, inaccurate or corrupt
data, transcription errors, a copyright or other intellectual
property infringement, a defective or damaged disk or other
medium, a computer virus, or computer codes that damage or
cannot be read by your equipment.

1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES -


Except for the “Right of Replacement or Refund” described in
paragraph 1.F.3, the Project Gutenberg Literary Archive
Foundation, the owner of the Project Gutenberg™ trademark,
and any other party distributing a Project Gutenberg™ electronic
work under this agreement, disclaim all liability to you for
damages, costs and expenses, including legal fees. YOU
AGREE THAT YOU HAVE NO REMEDIES FOR NEGLIGENCE,
STRICT LIABILITY, BREACH OF WARRANTY OR BREACH
OF CONTRACT EXCEPT THOSE PROVIDED IN PARAGRAPH
1.F.3. YOU AGREE THAT THE FOUNDATION, THE
TRADEMARK OWNER, AND ANY DISTRIBUTOR UNDER
THIS AGREEMENT WILL NOT BE LIABLE TO YOU FOR
ACTUAL, DIRECT, INDIRECT, CONSEQUENTIAL, PUNITIVE
OR INCIDENTAL DAMAGES EVEN IF YOU GIVE NOTICE OF
THE POSSIBILITY OF SUCH DAMAGE.

1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If


you discover a defect in this electronic work within 90 days of
receiving it, you can receive a refund of the money (if any) you
paid for it by sending a written explanation to the person you
received the work from. If you received the work on a physical
medium, you must return the medium with your written
explanation. The person or entity that provided you with the
defective work may elect to provide a replacement copy in lieu
of a refund. If you received the work electronically, the person or
entity providing it to you may choose to give you a second
opportunity to receive the work electronically in lieu of a refund.
If the second copy is also defective, you may demand a refund
in writing without further opportunities to fix the problem.

1.F.4. Except for the limited right of replacement or refund set


forth in paragraph 1.F.3, this work is provided to you ‘AS-IS’,
WITH NO OTHER WARRANTIES OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO
WARRANTIES OF MERCHANTABILITY OR FITNESS FOR
ANY PURPOSE.

1.F.5. Some states do not allow disclaimers of certain implied


warranties or the exclusion or limitation of certain types of
damages. If any disclaimer or limitation set forth in this
agreement violates the law of the state applicable to this
agreement, the agreement shall be interpreted to make the
maximum disclaimer or limitation permitted by the applicable
state law. The invalidity or unenforceability of any provision of
this agreement shall not void the remaining provisions.

1.F.6. INDEMNITY - You agree to indemnify and hold the


Foundation, the trademark owner, any agent or employee of the
Foundation, anyone providing copies of Project Gutenberg™
electronic works in accordance with this agreement, and any
volunteers associated with the production, promotion and
distribution of Project Gutenberg™ electronic works, harmless
from all liability, costs and expenses, including legal fees, that
arise directly or indirectly from any of the following which you do
or cause to occur: (a) distribution of this or any Project
Gutenberg™ work, (b) alteration, modification, or additions or
deletions to any Project Gutenberg™ work, and (c) any Defect
you cause.

Section 2. Information about the Mission of


Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new
computers. It exists because of the efforts of hundreds of
volunteers and donations from people in all walks of life.

Volunteers and financial support to provide volunteers with the


assistance they need are critical to reaching Project

You might also like