Bill DudneyJonathan Lehr
Bill WillisLeRoy Mattingly
Mastering JavaServer™ Faces
01_462071 ffirs.qxd 5/18/04 8:34 AM Page i
C1.jpg
01_462071 ffirs.qxd 5/18/04 8:34 AM Page iv
Bill DudneyJonathan Lehr
Bill WillisLeRoy Mattingly
Mastering JavaServer™ Faces
01_462071 ffirs.qxd 5/18/04 8:34 AM Page i
Wiley Publishing, Inc.Vice President and Executive Group Publisher: Richard SwadleyVice President and Executive Publisher: Robert IpsenVice President and Publisher: Joseph B. WikertExecutive Editorial Director: Mary BednarekEditorial Manager: Kathryn A. MalmExecutive Editor: Robert ElliottManaging Production Editor: Fred BernardiDevelopment Editor: Eileen Bien Calabro, Sharon NashProduction Editor: Felicia RobinsonMedia Development Specialist: Greg StaffordText Design & Composition: Wiley Composition Services
Copyright 2004 by Wiley Publishing Inc., Indianapolis, Indiana.
All rights reserved.
Published by Wiley Publishing, Inc., Indianapolis, IndianaPublished simultaneously in Canada
No part of this publication may be reproduced, stored in a retrieval system, or transmittedin any form or by any means, electronic, mechanical, photocopying, recording, scanning, orotherwise, except as permitted under Section 107 or 108 of the 1976 United States CopyrightAct, without either the prior written permission of the Publisher, or authorization throughpayment of the appropriate per-copy fee to the Copyright Clearance Center, Inc., 222 Rose-wood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Pub-lisher 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:[email protected].
Limit of Liability/Disclaimer of Warranty: While the publisher and author have used theirbest efforts in preparing this book, they make no representations or warranties with respectto the accuracy or completeness of the contents of this book and specifically disclaim anyimplied warranties of merchantability or fitness for a particular purpose. No warranty maybe created or extended by sales representatives or written sales materials. The advice andstrategies contained herein may not be suitable for your situation. You should consult witha professional where appropriate. Neither the publisher nor author shall be liable for anyloss of profit or any other commercial damages, including but not limited to special, inci-dental, consequential, or other damages.
For general information on our other products and services please contact our CustomerCare Department within the United States at (800) 762-2974, outside the United States at(317) 572-3993 or fax (317) 572-4002.
Trademarks: Wiley, the Wiley Publishing logo are trademarks or registered trademarks ofJohn Wiley & Sons, Inc. and/or its affiliates. JavaServer is a trademark of Sun Microsys-tems, Inc. All other trademarks are the property of their respective owners. Wiley Publish-ing, Inc., is not associated with any product or vendor mentioned in this book.
Wiley also publishes its books in a variety of electronic formats. Some content that appearsin print may not be available in electronic books.
Library of Congress Cataloging-in-Publication Data is available from the publisher. ISBN: 0-471-46207-1Printed in the United States of America10 9 8 7 6 5 4 3 2 1
01_462071 ffirs.qxd 5/21/04 2:15 PM Page ii
For Andrew, Isaac, Anna, Sophia, and Isabel—may you dream bigdreams and have the courage to pursue them. —BD
To my little Sunshine, who makes me see life in a different light. —BW
For my wife, Kathryn. —JL
01_462071 ffirs.qxd 5/18/04 8:34 AM Page iii
01_462071 ffirs.qxd 5/18/04 8:34 AM Page iv
Dedication iii
Acknowledgments xi
About the Authors xiii
Foreword xv
Introduction xviiThe Genius of JSF xviiJSF Makes Things Easy xxviiiWhat Is in the Book xixLayout of the Book xxiSummary xxiii
Part 1 Architecture of JSF 1
Chapter 1 JSF Patterns and Architecture 3Overview 3MVC and User Interfaces 4
MVC Pattern 4Model 2 - MVC for the Web 8
Implementing MVC 9Swing Collapsed MVC Strategy 10Struts Model-2 MVC Strategy 11JSF Component-Based Model-2 MVC Strategy 18
Composite Components 26Composite Pattern 27Swing Components and Containers 29Struts and Tiles 33JSF Component Trees 36
Contents
v
02_462071 ftoc.qxd 5/18/04 8:34 AM Page v
Component Events 38Observer Pattern 38Swing Event Listeners 40Struts Application Events 43JSF Events 44
Summary 46
Chapter 2 Elements of JSF 47Overview 48
Web Development 48UI Components 49
Standard UI Components 50Identifiers 53UI Component Trees 54Tree Manipulation and Navigation 55Facets 56Generic Attributes 60Data Models 61
Validation 62Validators 62Validator Registration 67Standard Validators 68
Conversion 69Converters 69Converter Registration 72Standard Converters 72
Events and Listeners 73UI Events 73Listeners 74Phase Identifiers 75Event Queuing and Broadcasting 76
Rendering 76Delegated Rendering 76Render Kits 78Registering Renderers 78Standard RenderKits 79
Summary 80
Chapter 3 JSF Request-Processing Life Cycle 81Overview 81
Faces Request Generates Faces Response 83Non-Faces Request Generates Faces Response 83Faces Request Generates Non-Faces Response 84Non-Faces Request Generates Non-Faces Response 85
Faces Context 85Accessing Context 86Component Tree 86
vi Contents
02_462071 ftoc.qxd 5/18/04 8:34 AM Page vi
External Context 87Flow Control 88Localization 88Message Queue 90
Event Queues 93Standard JSF Request-Processing Life Cycle 95
Restore View 96Apply Request Values 96Process Validations 98Update Model Values 100Invoke Application 101Render Response 101
Summary 103
Part 2 Elements of JSF 105
Chapter 4 JSF Configuration 107Overview 107Getting Started 108Introduction to Sample Application 108A Word about Web Applications 110
Web Application Structure 110Web Application Deployment Descriptor 113
Configuring a Web Application for JSF 114FacesServlet Mapping 115JSF Application Configuration Files 116Necessary Classes and Resources 117
Configuring a JSF Application 119Configuration File Format 119
Tool Support for JSF Configurations 152Building the Sample JSF Application 153Summary 154
Chapter 5 JSP Integration in JSF 155Overview 155Quick JSF/JSP Integration Example 156JSP Integration and the Render Response Phase 160
New JSF Requests 160Subsequent JSF Requests 166
JSF – JSP Integration Example 167Summary 173
Chapter 6 UI Components 175Overview 176Using Components 177
The View 184Subviews 186
Contents vii
02_462071 ftoc.qxd 5/18/04 8:34 AM Page vii
Value Binding 189Converting between Model Properties and UI Strings 198Processing Submitted Form Values 201
Validators 202Configuring Event Listeners 203Working with Tables 208
Using Facets 209A dataTable Example 210Using a panelGrid 215
Working with Select Lists 218Summary 222
Chapter 7 Navigation, Actions, and Listeners 223Overview 223Actions and Navigation 224
Implementing Application Actions 227Specifying Navigation Rules 229
Working with Forms 230Complex Forms 235Complex Navigation 252
Events and Listeners 261Implementing an ActionListener Method 262Implementing the ActionListener Interface 265Implementing a ValueChangeListener Method 268Implementing the ValueChangeListener Interface 271
Summary 274
Chapter 8 Validation and Conversion 275Overview 275Using Converters 277
Setting the converter Attribute in Input Tags 280Standard Converters 283
Using Custom Converters for Validation 285Displaying Error Messages 289Registering the Converter 289Using Converters to Validate Custom Value Types 290Converter Registration by Type 293
Using Validators 296Adding Validator Bindings in JSP 297Validator Methods 299Displaying Error Messages 300
Creating Custom Validators 300Adding Attributes to Custom Validators 302Creating a Custom Validator Tag 305
Conversion and Validation Processing 309Summary 312
viii Contents
02_462071 ftoc.qxd 5/18/04 8:34 AM Page viii
Part 3 Applying JSF 313
Chapter 9 Building JSF Applications 315Overview 315Architectural Overview 316JSF in the Architecture 318Connecting View, Controller, and Model Objects 319iBank Bill Payment Application 320
Login Screen 321Account Summary 322Review Historical Payments 323
Logging into iBank 324Configuration 328The Two-Tiered Model for Login 330Three-Tiered Model for Login 332
Welcome to iBank 335Making an iBank Payment 337Reviewing iBank Payments 339Summary 344
Chapter 10 Custom JSF Components 345Overview 345What Is a Custom Component? 346
Aggregate Component 346New HTML Generator 348New Client Type 349
Motivation for Building a Custom Component 349Aspects of Custom Components 351
Restore View 352Apply Request Values 353Process Validations 354Update Model Values 356Invoke Application 357Render Response 357
Custom Component Example 358UIScroller Component Code 359UIScroller Renderer Code 367UIScroller JSP Tag Code 375
Summary 382
Chapter 11 Converting a Struts Application to JSF 383Overview 384Defining the Example Problem: The SimpleBlogger 384
Use Cases 384Screen Design 387State Diagram 388Domain Classes 389
Contents ix
02_462071 ftoc.qxd 5/18/04 8:34 AM Page ix
The Struts Version of the SimpleBlogger 390Domain Classes 390Struts Configuration Files 390JSP Pages 392Form Classes 395Action Classes 398
The JSF Version of the SimpleBlogger 401Set Up the Environment 402Copy the Business Model Objects 405Convert the Struts ActionForm Classes to Managed Beans 405Convert the JSP Pages 408Build the Navigation Model 420Add the Action Handlers 421
Summary 428
Appendix What’s on the Web Site 431System Requirements 431
For Linux 432For Macintosh 432
References 433
Index 435
x Contents
02_462071 ftoc.qxd 5/18/04 8:34 AM Page x
xi
First and foremost, I would like to thank Christ, for all He has done in my lifeto teach me to be more than I was and to inspire me to be more than I am. Iwould also like to thank my wonderful wife Sarah; without her encourage-ment and love I’d be lost. And I’d also like to thank my great kids, who keeplife interesting. Andrew, Isaac, Anna, and Sophia, you are the definition of joy.Also, I can’t begin to express my thanks to Chris Maki who spent many a latehour reviewing the book and making it much better than it was. Thanks againChris! Finally I’d like to thank Ed Burns for all his feedback late in the cycleunder a looming deadline; it’s a better book because of his feedback. —BD
Once again, I am indebted to my coauthor, Bill Dudney, for inviting me to par-ticipate in the writing of this book, as well as for his valuable input. I am alsograteful for the contributions of Eileen Bien Calabro and Chris Maki, whichhave dramatically improved the content both in terms of readability and (let’shope!) correctness.
Writing several chapters of a technical book such as this in one’s spare timeis at best a challenging proposition. It might have proven difficult indeed tokeep things running smoothly at work were it not for my friend Carl Lind-berg’s remarkable craftsmanship and extraordinary diligence. He also borewith good cheer my frequent murmuring about my impossible schedule,while acting as my sounding board and contributing a number of useful sug-gestions. Many thanks, Carl!
Above all, I thank my dear wife Kathryn, who often bore the brunt of thisdemanding project, tending to things that I no longer had time for and keep-ing up social obligations that I often had to dodge. Her indispensable patience,love, and support kept me going when the work got overwhelming. I am alsograteful to our family and friends for being so sympathetic to our situation,and for their repeated offerings of encouragement. —JL
Thank you to Chris Maki for his valuable input to this book. —BW
Acknowledgments
03_462071 flast.qxd 5/21/04 2:16 PM Page xi
03_462071 flast.qxd 5/18/04 8:36 AM Page xii
Bill Dudney is a Java architect with Object Systems Group. He has been build-ing J2EE applications and software for 6 years and has been doing distributedcomputing for almost 15 years. Bill has been using EJB since he was at InLineSoftware and the first public beta was released. Bill has built several J2EEapplications as well as tools to help others do the same. He is also a coauthorof Jakarta Pitfalls and J2EE AntiPatterns, both from Wiley.
Jonathan Lehr is a software developer, architect, mentor and trainer with over20 years of industry experience, including 12 years of object-oriented program-ming. He is coauthor of Jakarta Pitfalls (Wiley), and has written and taughtcourses on a variety of programming topics delivered to thousands of devel-opers throughout the United States.
For the past 8 years, he has helped design and implement large-scale e-commerce applications in Java and Objective C for Fortune 500 financial andtelecommunications companies. He currently leads a framework developmentteam that provides reusable Struts-based components and infrastructureenhancements for use by development teams at a major financial institution.
Bill Willis has over 10 years of experience in the software industry managingand developing mission-critical systems and innovative, industry-leadingproducts and services. He is an expert in object-oriented methods and Pattern-driven design and development, and has used Java since its introduction. Heis currently the director of engineering and technology at ObjectVenture Inc.,where he focuses on next-generation, pattern-based tools and technology thathelp less experienced developers visualize and build well-designed software.He is also the director of PatternsCentral.com, a community portal devoted to“all things Patterns.”
About the Authors
xiii
03_462071 flast.qxd 5/18/04 8:36 AM Page xiii
LeRoy Mattingly is a senior software engineer with Tecton Software, Inc. Hehas over 10 year’s experience building large scale object–oriented systems. Hisspecialties include project mentoring, use-case–driven development, andapplying adaptive process improvements for large software development pro-jects. In addition, he is co-owner and lead software engineer of OSGTools, asubsidiary company of Object Systems Group. At OSGTools, he is the creatorand lead software engineer of The Integrator—a specialized tool for authoringand managing the use case process.
xiv About the Authors
03_462071 flast.qxd 5/18/04 8:36 AM Page xiv
xv
Foreword
JavaServer Faces is a holistic solution to several longstanding problems facingsoftware developers and the customers who consume the software. For theend user, JavaServer Faces holds the promise of an easier, more intuitive usageexperience for Web-based applications. For software developers, JavaServerFaces provides a standard, object-oriented, easy-to-use application program-ming interface (API) that takes much of the pain out of bringing a great userexperience to the world of Web applications. JavaServer Faces gives users thepower, flexibility, and performance that have previously been addressed onlyin a piecemeal fashion.
JavaServer Faces was developed by a community of Web applicationexperts assembled by the Java Community Process. These experts are the peo-ple behind Jakarta Struts, Oracle Application Server, Sun Java Studio, IBMWebSphere Studio, ATG, and many other programs in the Web applicationdevelopment space. Their collective wisdom was brought to bear on the prob-lem of how to take the best patterns from the existing technologies that solvethe same problems and combine them into a cohesive whole, as well as fillingin the gaps not filled anywhere to date. JavaServer Faces combines the ubiq-uity of JSP and servlets, the simplicity of JavaBeans, the power of J2EE, and thecommon-sense chutzpah of frameworks like Jakarta Struts to bring you thebest-of-breed way to develop the user interface for a Web application.
I’d like to take this opportunity to thank the members of the Java Commu-nity Process Expert Group who contributed directly to the development ofJavaServer Faces, also the team of dedicated engineers that brought the firstreference implementation to market, and the early adopters in our initialaccess and beta program who discovered the hard bugs and had the patienceto wait for us to get it right the first time.
03_462071 flast.qxd 5/18/04 8:36 AM Page xv
Now, to the matter of Mastering JavaServer Faces. This book is all about get-ting you up to speed and productive with JavaServer Faces quickly, and pro-viding enough depth to keep you on track once you are. The authors havedone a great job of taking the complexity inherent in providing a complete APIfor Web application user interfaces and pulling out the simple concepts onwhich this API was built. If you’ve read any of the author’s other books, youknow that the author focuses on pitfalls and anti-patterns; this book alsoemphasizes these things.
Here are just a few of the reasons why I recommend this book: the authorkeeps the text readable by foreshadowing more interesting content; includeschapters that “put it all together”; provides examples implemented in severaldifferent ways, for example, a JavaBeans version and an EJB version; uses theUnified Modeling Language (UML effectively to get the point across instantly;and, most importantly, provides ready-to-use patterns and samples you canimmediately work into your application. All of these things combine to makethis the book you keep handy at your elbow as you develop JavaServer Facesapplications.
Ed Burns, JSF Implementation Lead and Co-Specification Lead
xvi Foreword
03_462071 flast.qxd 5/18/04 8:36 AM Page xvi
JavaServer Faces (JSF) is an exciting new technology that will change the waywe build user interfaces for Java 2 Enterprise Edition applications. With theintroduction of JSF, we can finally create user interfaces simply with a set ofreusable components. And with a component-based framework, Web applica-tions are finally on a more level playing field with client-based User Interface(UI) frameworks such as Swing. Now, Web developers will be able to use andreuse components off the shelf in their applications so we will see tool supportand components implemented for JSF.
The Genius of JSF
The genius of JSF is that we only have to learn the UI programming modelonce, and then apply that knowledge to any JSF-compliant component that wewant to use. Now that we finally have a standard component model, pro-gramming for the Web is much easier to learn and to do.
What is a component-based, Web-tier UI framework? A component is some-thing that has known attributes and behaviors, i.e., all the components in JSFhave at least a base set of attributes and behaviors in common. A componentmodel allows you to reuse components that come from a third party withouthaving to learn a new component model (the model is standard). Typically,components fit into a part/whole hierarchy (see the Composite Pattern dis-cussion in Chapter 2, “Elements of JSF”) and can be composed into more com-plex components.
The component-based model is beneficial to the handling of the user action.A user action, such as a button click, flows through a well-defined process
Introduction
xvii
03_462071 flast.qxd 5/18/04 8:36 AM Page xvii
from the button click to the business logic that performs the requested process.JSF provides well-defined points for your code to plug into the flow and beexecuted.
The component-based model also allows developers to focus on providinggreat features instead of trying to focus on two or three different models forbuilding Web-based user interfaces. It also allows the promise of reusable off-the-shelf components in the future. In the same way that you can purchase aSwing-based UI component that plots graphs of data, you will be able to buyoff-the-shelf JSF components that provide similar functionality.
JSF Makes Things Easy
Another great thing is that JSF offers a standard, ubiquitous technology tolearn instead of the fragmented landscape that currently exists in the world ofJ2EE Web-based UI frameworks. Further, JSF will almost certainly be includedin the J2EE specification in the future, ensuring that all the major vendors willhave an implementation included out of the box. Eventually, there will be amajor body of knowledge and mindshare behind it so that you will have lotsof resources to help you implement your applications.
Lets take a quick look at how the JSF component model makes building Webapplications easy. The following little sample application will take a cus-tomer’s first and last name and store it. The UI is very simple: two labels, twotext fields, and a button to save the input. The user interface is rendered in Fig-ure Intro.1 below.
Figure Intro.1 Sample customer input form.
The components involved in this user interface are built in a JSP with the fol-lowing code. The important parts will be discussed below in more detail.
xviii Introduction
03_462071 flast.qxd 5/18/04 8:36 AM Page xviii
Listing Intro.1 CustomerInput JSF page.
This code creates a form (which contains the rest of the components) andthen creates the subsequent components. This group of components, rooted atthe form, is known as a component tree. You will learn all about componenttrees later in the book, for now think of the tree as a collection of componentsthat know which component is their parent and which components are theirchildren. The cool thing about this page is that the components on it are active.As a request comes in and JSF processes it, the components get to play anactive role in how the application acts. For example, the components can postevents that are later used to process business logic. So, in our little examplehere each of these buttons is able to invoke a different piece of logic by postingevents.
What Is in the Book
This book is about the JSF UI component model for building Java applicationsfor the Web. The book is practically focused, but has enough information onthe programming model to allow you to understand why you are doing whatyou are doing. This should allow you to have not only a broad understandingof JSF, but also a deep understanding of how the framework works.
Introduction xix
03_462071 flast.qxd 5/18/04 8:36 AM Page xix
How to integrate your UI with the back-end persistent state will also be cov-ered. In a typical J2EE Web application, there are at least three logic tiers, thefront-end, or Web, tier; the application tier; and the database tier, where thepersistent state of the application is stored. We find this three-tiered approachto building applications in many J2EE applications today. Figure Intro.2 showshow JSF will fit into the three-tier scenario.
Figure Intro.2 Three-tier JSF configuration.
The Web tier of a J2EE application is based on HTML sent to a browser. TheHTML is dynamically generated via JSPs and/or servlets that delegate theapplication logic to plain old Java objects (POJOs), which interact with the data-base using JDBC (the application tier) to store and retrieve data for the applica-tion. However, in enterprise-scale applications, the application tier will beimplemented in EJBs either as sessions or entities, or some combination of both.
With EJBs in the picture, the application is made of four tiers: Web,JSP/Servlet, EJB, and database. JSF fits into the JSP/Servlet tier and provides acomponent-based approach to building applications. JSF provides a way tobuild user interfaces and delegate the business processing to the next layer(that is, the EJB layer). We will see a lot more about this in Chapter 1, “JSF Pat-terns and Architecture.” Application logic can take the form of POJOs orEJBs—JSF integrates nicely with either. This book shows you how to build JSFapplications that interact with either EJBs or POJOs. Figure Intro.3 shows thefour-tier configuration that we would see in a typical JSF application.
The book will also cover the technical details of JSF so that you will be ableto do more than simply follow a cookbook; rather, you will be able to inventyour own recipes. For example, the validation coverage in Chapter 7, “Navi-gation, Actions, and Listeners,” not only describes how you will ensure thatthe data you put into the database is valid but also shows the details of howvalidation works in JSF. Armed with this knowledge, you will be able to confi-dently build applications that validate their data, and if needed, be able tobuild your own custom validators.
Single JVM
Browser
JSF
JSP Servlet
ApplicationLogic
(POJO)DatabaseHTML over HTTP JDBC
xx Introduction
03_462071 flast.qxd 5/18/04 8:36 AM Page xx
Figure Intro.3 Four-tier JSF configuration.
Layout of the Book
The book is laid out in three parts that cover various aspects of JSF. The firstpart, “Architecture of JSF,” covers the big architectural picture of JSF. The next part, “Elements of JSF,” covers the various pieces of the JSF componentmodel. The last part, “Applying JSF,” brings the other two parts together, cov-ering issues related to using JSF in applications.
The first part covers the architectural aspects of JSF, from the patterns thatare used in the implementation to the life cycle of a typical JSF request/response pair. This part will provide you with a broad understanding of howJSF is put together and functions. This part will provide you with the knowl-edge you need to understand the more concrete pieces of JSF. The contentassumes that you are familiar with Java programming for the Web and thatyou have at least some exposure to general design patterns. You will also begiven a broad overview of the components of JSF. The following chapters arein this part:
Chapter 1: JSF Patterns and Architecture. This chapter covers the archi-tecture of JSF by discussing the patterns used in its implementation. Thechapter also compares JSF to its to greatest influences, Struts and Swing.
Chapter 2: Elements of JSF. This chapter provides an introduction to thecomponent mode of JSF by going over briefly the various APIs thatmake up the component model. This chapter provides a brief summaryof the next major section. If you find something here that is interesting,you can jump forward to the chapter that covers that topic in detail.
Single JVM
Browser
JSF
JSP Servlet
EventHandlerClasses
HTML over HTTP
CMP or BMP
Single JVM
ApplicationLogic(EJB)
Database
Introduction xxi
03_462071 flast.qxd 5/18/04 8:36 AM Page xxi
Chapter 3: JSF Request-Processing Life Cycle. This chapter covers theway that JSF responds to requests and provides the rendered versions ofcomponents back to the requestor. Understanding this life cycle is cru-cial to building JSF applications.
Part 2, “Elements of JSF,” covers in detail all the abstractions that make upJSF. The topics covered include components, events, validation, and so on.After reading this section, you will have a broad understand of all of JSF aswell as practical knowledge of how to use JSF. Each chapter in this section willfocus on a different aspect of the JSF component model and how that aspectfits into building real-world applications. The following chapters are in thissection:
Chapter 4: JSF Configuration. This chapter deals with what you have todo to configure your JSF application. Details of the faces-config.xmlfile and what to add to your Web.xml file as well as how to get theTagLibs setup will be covered.
Chapter 5: JSP Integration in JSF. This chapter covers the details of howJSF integrates with JSPs through the custom tag feature in JSP imple-mentations. After you read this section, you will have a detailed under-standing of how the integration works. We will also cover each of thecustom tags required for JSPs to be part of any JSF implementation.
Chapter 6: UI Components. This chapter covers the component API indetail. After reading this chapter, you will know how to use UICompo-nents to build your user interface. You will be comfortable with the stan-dard components and how they are used in a typical JSF application.You will also understand the various pieces that make up a componentand how they are involved in the request-response life cycle.
Chapter 7: Navigation, Actions, and Listeners. This chapter discussesthe navigation and event model in JSF. When you are finished with thischapter, you will understand the way that navigation works in a JSF.This chapter also discusses events and how they are used to manage thenavigation and invoke state changes in your applications.
Chapter 8: Validation and Conversion. This chapter provides informa-tion on ensuring that the data that you store meets the business rules foryour application. After reading this chapter, you will understand thevalidation and conversion model inherent in JSF. You will be able to usethe built-in Validators and Converters that come with JSF as well as beable to create your own.
xxii Introduction
03_462071 flast.qxd 5/18/04 8:36 AM Page xxii
Part 3, “Applying JSF,” covers using JSF in the real world to build applica-tions. Specifically covered here are integrating JSF user interfaces with thebusiness tier (be it EJB or POJO), building custom components to render yourown user interface components, and converting your existing Struts applica-tions to JSF. The following chapters are included in this part:
Chapter 9: Building JSF Applications. This chapter covers the detail ofhow to integrate your application with the technology actually used tobuild enterprise applications. Both EJB integration and POJO throughJDBC will be covered. After reading this chapter, you will understandhow to build real-world JSF applications that put enterprise data into abrowser so that users can manipulate and save that data.
Chapter 10: Custom JSF Components. This chapter shows you how tobuild your own custom components. After reading this chapter, you willbe comfortable with building a component that understands how to ren-der itself as well as integrate itself with a RenderKit. You will alsounderstand how to validate the new component and how events can bequeued by the component to invoke custom application logic.
Chapter 11: Converting a Struts Application to JSF. This chapter demon-strates in detail how you can move your application from Struts to JSF.After reading this chapter, you will be comfortable converting yourpages and application logic to JSF.
Summary
We are very excited about the promise of JSF and what it means to the averageJ2EE application developer. With JSF, you will be able to build consistentreusable user interfaces for the Web that interact in well-defined ways withyour business process code. It is indeed a good time to be a geek. We hope thatyou enjoy and get as much out of this book as we did in writing it.
Introduction xxiii
03_462071 flast.qxd 5/18/04 8:36 AM Page xxiii
03_462071 flast.qxd 5/18/04 8:36 AM Page xxiv
PA R T
One
Architecture of JSFChapter 1: JSF Patterns and ArchitectureChapter 2: Elements of JSFChapter 3: JSF Request-Processing Life Cycle
04_462071 PP01.qxd 5/17/04 10:10 AM Page 1
04_462071 PP01.qxd 5/17/04 10:10 AM Page 2
3
As with any other framework, gaining an understanding of how JSF isdesigned is crucial to applying it correctly and transitioning from other similarframeworks. This chapter will discuss the Model-View-Controller (MVC)architectural pattern, which is commonly used in modern user interfaceframeworks, and how it has been adopted for the Web (and JSF). We’ll thentake a more detailed look at how the JSF framework implements MVC andother patterns that are commonly used with MVC. This will by no means be anexhaustive or academic patterns study, but it will be enough to highlight theJSF architecture and show you what you can accomplish with it. While doingso, it will be useful to put JSF in perspective with two other frameworks thathave heavily influenced it and to which it will undoubtedly be comparedagainst: Swing and Struts.
Overview
Patterns typically exist at a higher level of abstraction than the implementa-tions they describe. Indeed, this is one of the primary benefits of patterns—todescribe a general solution to a recurring problem. As such, the purpose of apattern is not to provide a specific implementation but to provide a reusabledesign with constraints on its use. At implementation time, the application of a pattern solution will vary according to your specific needs and will be
JSF Patterns and Architecture
C H A P T E R
1
05_462071 Ch01.qxd 5/18/04 8:36 AM Page 3
influenced by any number of factors (a good example being the programminglanguage you use). However, it will always adhere to the spirit of the pattern,which is just another way of saying that it will satisfy the constraints that a pat-tern places on its solution.
It is not uncommon then for a pattern to have any number of differentimplementations. Here we refer to such an implementation as a strategy. Donot confuse the term strategy here with the Gang of Four (or GoF) pattern of thesame name (Gamma, Helm, Johnson, and Vlissides 1996). We use the termstrategy here in the same manner in which you will find in Core J2EE Patterns(Alur, Crupi, and Malks 2003). Most documented strategies provide the mostcommon implementations of a particular pattern, thereby aiding in the com-munication of a pattern solution’s lower-level aspects.
In this chapter, we will typically start out with an informal pattern descrip-tion and then follow with the strategy used for implementing it in each of thethree frameworks we are focusing on here. You are encouraged to study thesepatterns and their various implementation strategies outside of our coveragehere to get a fuller understanding of how each framework is designed.Employing such a process should yield a better understanding of how JSFattempts to solve some of the same problems that Swing and Struts were facedwith. In the end, you should not be surprised to see how heavily JSF is influ-enced by both frameworks.
MVC and User Interfaces
MVC was first popularized with Smalltalk (Goldberg & Robson 1983) and isnow used in many modern user interface frameworks. One of the primarybenefits of MVC is that it provides reusable components for interactive userinterfaces. Swing does this admirably for rich Java clients, while Struts does soto a lesser extent on the Web. Even though the introduction of Tiles to Strutsprovides more reuse, the components are still more page-centric as opposed toSwing’s more fine-grained widget-centric approach. Like Struts, JSF is tar-geted at Java Web applications, but moves closer to Swing with its concentra-tion on reusable user interface widgets (or components).
MVC PatternWe begin by describing the traditional form of MVC and then discuss how ithas been adapted for the Web. Each of the three frameworks is then examined,and their respective implementations of this common pattern are uncovered.
The intent of this pattern is to partition interactive applications into threeseparate components: Model, View, and Controller. The Model represents coreapplication data and functional logic, the View renders the data and displays
4 Chapter 1
05_462071 Ch01.qxd 5/18/04 8:36 AM Page 4