x CONTENTS2 Building web applications 27 2.1 Building web applications with servlets 29 The eMotherEarth servlet application 29 Evaluating the servlet approach 50 2.2 Building web applic
Trang 1M A N N I N G
Neal Ford
STRUTS TAPESTRY COMMONS VELOCITY JUNIT AXIS COCOON INTERNETBEANS WEBWORK
JAVA WEB
DEVELOPMENT
Trang 3Art of Java Web Development
Trang 5Art of Java Web Development
STRUTS, TAPESTRY, COMMONS, VELOCITY, JUNIT, AXIS, COCOON, INTERNETBEANS, WEBWORK
N EAL F ORD
M A N N I N G
Greenwich(74° w long.)
Trang 6For online information and ordering of this and other Manning books, go to
www.manning.com The publisher offers discounts on this book when ordered in
quantity For more information, please contact:
Special Sales Department
Manning Publications Co.
209 Bruce Park Avenue Fax: (203) 661-9018
Greenwich, CT 06830 email: orders@manning.com
©2004 by Manning Publications Co All rights reserved.
No part of this publication may be reproduced, stored in a retrieval system, or transmitted,
in any form or by means electronic, mechanical, photocopying, or otherwise, without
prior written permission of the publisher.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps.
Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books they publish printed on acid-free paper, and we exert our best efforts to that end.
Manning Publications Co Copyeditor: Liz Welch
209 Bruce Park Avenue Typesetter: Dottie Marsico
Greenwich, CT 06830 Cover designer: Leslie Haimes
ISBN: 1-932394-06-0
Printed in the United States of America
1 2 3 4 5 6 7 8 9 10 – VHG – 08 07 06 05 04 03
Trang 7To Chuck,
who still teaches me stuff daily
Trang 9brief contents
P ART I T HE EVOLUTION OF WEB ARCHITECTURE
AND DESIGN 1
1 ■ State-of-the-art web design 3
2 ■ Building web applications 27
3 ■ Creating custom JSP tags 61
4 ■ The Model 2 design pattern 91
Trang 10viii BRIEF CONTENTS
P ART III B EST PRACTICES 327
18 ■ Web services and Axis 543
19 ■ What won’t fit in this book 563
Trang 11contents
preface xvii acknowledgments xix about the book xxi about the cover illustration xxx
P ART I T HE EVOLUTION OF WEB ARCHITECTURE
AND DESIGN 1
1 State-of-the-art web design 3
1.1 A brief history of Java web development 4
1.2 The importance of design patterns 6
The Model-View-Controller design pattern 7 ■ The emergence of Model 2 9 ■ Evolution 10
Trang 12x CONTENTS
2 Building web applications 27
2.1 Building web applications with servlets 29
The eMotherEarth servlet application 29 Evaluating the servlet approach 50
2.2 Building web applications with JSP 50
The JSP eMotherEarth application 51 Evaluating the JSP approach 59
2.3 Summary 60
3 Creating custom JSP tags 61
3.1 The case for custom tags 62
3.2 The tag interfaces 63
The Tag interface 63 ■ The IterationTag interface 64 The BodyTag interface 65
3.3 Building simple tags 66
The HtmlSqlResult tag 66 ■ Registering the tag 71
3.4 Validating tag attributes 75
Adding DbPool to the application tag 75
3.5 Using prebuilt tags 80
Using JSTL 81 ■ Using other taglibs 84
3.6 Custom tag considerations 86
Resource usage 87 ■ Building a framework 88
3.7 Now that we’re here, where are we? 88
3.8 Summary 89
4 The Model 2 design pattern 91
4.1 Using Model 2 as your framework 92
The Model 2 schedule application 93 Options in Model 2 116
4.2 Parameterizing commands with controller servlets 117
An example of parameterizing commands 118 Advantages and disadvantages 127
4.3 Summary 128
Trang 13CONTENTS xi
P ART II W EB FRAMEWORKS 131
5 Using Struts 133
5.1 Building Model 2 Web applications with Struts 134
The Struts schedule application 134 ■ Value objects as form beans 136 ■ Objectifying commands with Struts’ actions 137 Configuring Struts applications 139 ■ Using Struts’ custom tags
to simplify JSP 142 ■ Internationalization with Struts 145 Struts’ support for data entry 147 ■ Declarative validations 151
6.3 A simple Tapestry application 162
Tapestry Hello, World 162
6.4 The Tapestry framework 167
Framework classes and interfaces 167 ■ Components 170
Trang 14DataExpress 230 ■ InternetBeans Express 233
8.3 InternetBeans Express components 234
ixPageProducer 234 ■ ixComponents 236
8.4 Scheduling with InternetBeans 237
Data connectivity 238 ■ The View page 242 ■ The Add page 245 ■ Validations 249
8.5 JSP custom tags 255
8.6 Evaluating InternetBeans Express 257
Documentation and samples 257 Using InternetBeans Express 258
9.4 Scheduling with Velocity 269
The View page 271 ■ The Add page 274 Validations 278
Trang 16xiv CONTENTS
P ART III B EST PRACTICES 327
12 Separating concerns 329
12.1 Using interfaces to hide implementation 330
JDBC interfaces 331 ■ Interfaces in frameworks 331 Decoupled classes 332
12.2 Using JavaBeans 333
Model beans 334
12.3 Using Enterprise JavaBeans 337
The EJB architecture 338 ■ Porting from JavaBeans to Enterprise JavaBeans 340 ■ Using EJBs in web frameworks 360
Managing JNDI context 361
12.4 Performing validations with model beans 362
Client-side validations 362 Building client-side validations from the server 365
12.5 Summary 368
13 Handling flow 371
13.1 Application usability options 372
Building the base: eMotherEarth.com 372 ■ Page-at-a-time scrolling 378 ■ Sortable columns 384
User interface techniques in frameworks 389
13.2 Building undo operations 390
Leveraging transaction processing 391 ■ Using the Memento design pattern 394 ■ Undo in frameworks 401
13.3 Using exception handling 401
The difference between technical and domain exceptions 401 Creating custom exception classes 402 ■ Where to catch and handle exceptions 403 ■ Exceptions in frameworks 406
Trang 17CONTENTS xv
14.2 Common performance pitfalls 421
Object creation 422 ■ Extraneous object references 424 String usage 426
14.3 Pooling 427
Simple object pools 427 ■ Soft and weak references 428 Commons pools 433 ■ Pooling in frameworks 440
14.4 Designing for scalability 440
When to scale up to EJB 441 Molding your architecture for the future 441
15.2 Other resources you need to manage 470
Effectively using JNDI 470 ■ Using lazy instantiation 472 Working with web collections 472
15.3 Summary 473
16 Debugging 475
16.1 Debugging web applications 476
16.2 Debugging with the SDK 483
Starting the debugger 483 ■ Running the debugger 486 Breakpoints and steps 489 ■ Accessing variables 490 Effectively using jdb 492
16.3 Debugging with IDEs 493
Debugging with NetBeans 493 ■ Debugging with JBuilder 498 Differences between debuggers 502
16.4 Evaluating debuggers 505
16.5 Debugging in frameworks 506
Struts 506 ■ Tapestry 507 ■ WebWork 507 InternetBeans Express 507 ■ Velocity 508 ■ Cocoon 508
Trang 18xvi CONTENTS
16.6 Logging 508
General logging concepts 509 ■ SDK logging 512 log4j logging 516 ■ Choosing a logging framework 519 Logging in frameworks 519
16.7 Summary 520
17 Unit testing 521
17.1 The case for testing 522
Agile development 522 ■ Unit testing in web applications 524
17.2 Unit testing and JUnit 525
Test cases 525 ■ Testing entities 525 ■ Running tests 528 Test suites 529 ■ Testing boundaries 530 ■ Tool support 534
17.3 Web testing with JWebUnit 536
JWebUnit TestCases 537 ■ Testing complex elements 539
17.4 Summary 541
18 Web services and Axis 543
18.1 Key concepts 544
18.2 Axis 545
Architecture of Axis 546 ■ Axis tools 547
18.3 Calling web services 551
18.4 eMotherEarth web services 553
Configuration 553 ■ Orders 556 ■ Calling the web service 559
19.2 HTML and the user interface 566
HTML/XHTML 567 ■ Cascading Style Sheets 567
19.3 JavaScript 568
19.4 Summary 569
bibliography 570 index 571
Trang 19preface
In ancient China (approximately 500 B.C.), Sun Tzu wrote The Art of War In it, he
described the state of the art in warfare The book took a universal approach,describing wide-ranging topics that related to one another only through how they
applied to warfare In 1961, Julia Child published the classic Mastering the Art of
French Cooking In her book, she described the essentials of mastering French
cooking Her book covered an extensive array of topics, including both kitchentechniques and recipes
Both of these influential books offered a comprehensive look at the currentthinking in their fields Each covered a variety of topics, discussing specific tech-niques and underlying theories They included concrete, practical advice, andthey talked about the tools available to make the job of warfare (or cooking) easier
Art of Java Web Development strives for the same breadth and depth of coverage for
web development in Java It is not a random selection of topics Rather, it passes topics that web developers must master to deliver state-of-the-art software Italso examines the evolution of the cutting edge in web development architectureand design, describes the best tools (or weapons) available to developers, andexplains specific, practical techniques for improving your web applications Most development books today fall into one of two categories: API or best prac-tices The API books focus on a single API, either from J2EE and Java or, for exam-
encom-ple, an open-source project A perfect example is Manning’s excellent Struts in
Action, by Ted Husted et al It takes you through everything you need to know
Trang 20xviii PREFACE
about how to use Struts The best (or worst) practices books focus on individualtopics, examining design patterns and coding samples that represent the best (or
worst) ways to perform a certain task Art of Java Web Development overlaps some of
the topics from these other types of books, but it does so in a synergistic manner,discussing how all these pieces (and others) combine to create real-world webapplications
Trang 21acknowledgments
Writing any book is a daunting task, and the nature of this book made it evenmore so This means that my supporting structure (i.e., my family and friends)suffered with and supported me even more than usual For that, they have myundying gratitude First, to all my immediate and extended family, thanks for allyour support, especially my mother, Hazel, who bears the most responsibility forwho I am today Also, thanks to my dad, Geary, along with Sherrie, Elisha, and thewhole menagerie for their support I would also like to thank Lloyd, Michelle,John, Madison, and Max (a force of nature) for all their fun and companionship,along with Mechelle, Mark, Wyatt, and Wade The whole Shephard clan deserves
a nod, because they care a lot more about me learning to cook the secret familyrecipe for Death by Candied Yams than what I put to paper
I would also like to thank my surrogate family here in Atlanta, as fine a bunch
of people as you will ever meet: Margie, Wright, Melissa, Julie, Walker, Jim, Randy,and Karen They have taken Candy and me into their family and made us feel likeone of them
There are several instructors whom I feel I should acknowledge as well Being
an instructor myself, I have insight into what it takes to do it right, and these ple showed me all I know about it I would like to thank K N King at GeorgiaState for excellence in computer science, Robert Goetzman for teaching me toappreciate literature at a finer level, and James Head for being the finest instruc-tor whose classes I’ve had the pleasure to attend Dr Head and the others are
Trang 22imag-it is possible to have an interesting and diverse life.
I would also like to thank everyone at Manning, the best publisher I’ve everencountered Everyone there from the publisher down embodies what a bookcompany should be A special thanks goes out to my technical editor, Luigi Vig-giano, for keeping me honest, along with the rest of the Manning cast, including(but not limited to) Marjan Bace, Liz Welch, Mary Piergies, Susan Capparelle,Ann Navarro, and Dottie Marsico I would also like to thank all the technicalreviewers who spent a great deal of time to make this book better: Jason Carreira,Erik Hatcher, Shahram Khorsand, Howard Lewis Ship, Steve Loughran, TedNeward, Eitan Suez, and Luigi Viggiano I appreciate their insights, comments,criticisms, and feedback
It is virtually impossible to exist in this field if you don’t have activities that fallcompletely outside the technical realm For that I have other circles of friends,who are vaguely aware of what I do for a living, but frankly could care less Theseinclude my neighbors, Jamie, Diane, Kitty, and Gail Another large support groupconsists of all my triathlete buddies, who only know me as the slow guy behindthem: Jon, Joan, Jane, and Robert all fall into that group of people who help keep
me sane
There aren’t many people who span all the above groups (plus some othergroups that I didn’t even mention) In fact, there is really only one: Terry, whodeserves special thanks for support and friendship, who is a good travel partner,geek, and Tri-geek And thanks to Stacy for letting him do all that stuff
Last but certainly not least is the person who both likes and dislikes this bookthe most My beautiful and wonderful wife, Candy, whom I love more than any-thing, has spent far too long in the company of only Winston and Parker anddeserves more of my time Honey, this book is finally done, and I’m all yours again
Trang 23about the book
This book is for every Java web developer, regardless of his or her level of tise It is designed primarily for intermediate to advanced developers, who under-stand the specifics of the various web APIs in Java but haven’t yet mastered the bestway to apply them It is perfect for developers who have heard terms like Model-View-Controller and Model 2, but weren’t present for the series of events that led
exper-to the widespread adoption of these best practices It is also perfect for designersand architects of web applications because it discusses the implications of archi-tecture and design at every opportunity
This book is also well suited to developers who have looked at (and possiblystruggled with) one of the many web frameworks on the market It is unique in itscoverage of web frameworks, giving equal weight to six different frameworks andcomparing them on equal ground Whether you are planning to use a framework
or you want to write your own, understanding the similarities and differences
between the existing frameworks will save you a great deal of time Art of Java Web
Development also illustrates new possibilities for those who are using a framework
but aren’t happy with it
In addition, this book is aimed at developers who must create applications inthe real world Many of the best practices books treat each tip as the sole focus of
a chapter, with no discussion of integrating it into a real application Real tions are messy, requiring lots of moving parts working together seamlessly Thebest practices in this book are presented in the context of a working e-commerce
Trang 24applica-xxii ABOUT THE BOOK
application, with all the places that the real world intersects with the academia ofthe pattern discussed
How this book is organized
Art of Java Web Development consists of three parts It begins with coverage of the
his-tory of the architecture of web applications, highlighting the uses of the standardweb API to create applications with increasingly sophisticated architectures Thediscussion leads to the development of industry-accepted best practices for archi-
tecture Instead of simply pronouncing one architecture as the best, Art of Java Web
Development shows the history and evolution of each architecture
The second part of the book provides a unique overview of the most popularweb application frameworks Trying to evaluate a framework is difficult because itsdocumentation typically stresses its advantages but hides its deficiencies Thisbook builds the same application in six different frameworks, encouraging you toperform an “apples to apples” comparison The last chapter of part 2 provides acandid evaluation of the pros and cons of each framework to assist you in making
a decision or in evaluating a framework on your own
The selection of the correct framework is only the beginning of the life cycle of
an application Part 3 examines best practices, including sophisticated user face techniques, intelligent caching and resource management, performance tun-ing, debugging, testing, and web services
inter-Part 1
Chapter 1 serves as the jumping-off point for the book It highlights all the topics
to come in the subsequent chapters and explains my primary motivation for ing the book
Chapter 2 begins our discussion of the evolution of web applications The idea
behind this chapter is to present an application built by a developer who is verygood with Java and understands the web APIs but hasn’t yet applied best practicesand architecture The first pass at the application uses only servlets (which was theonly tool available when the web APIs first debuted) Then we build the sameapplication using just JSP In both cases, we highlight the strengths and weak-nesses of the resulting applications
Chapter 3 carries the evolution a step further with custom tags It takes the JSP
application built in the second chapter and improves it using custom JSP tags
Chapter 4 represents the culmination of the evolution of architecture and
design Here, we rewrite our sample application as a Model 2 application You’llalso learn how to leverage design patterns to improve the Model 2 application