About the AuthorsEd Burns is a senior staff engineer at Sun Microsystems.Ed has worked on a wide variety of client- and server-side Web technologies since 1994, including NCSAMosaic, Mozilla, the Sun Java Plugin, Jakarta Tomcat,and most recently, JavaServer Faces. Ed is currently theco-spec lead for JavaServer Faces. Find Ed’s blog andother goodies at http://purl.oclc.org/NET/edburns/.Chris Schalk is a Developer Advocate and worksto promote Google’s APIs and technologies. He iscurrently engaging the international Web developmentcommunity with the new Google App Engine andOpenSocial APIs. Before joining Google, Chris was aPrincipal Product Manager and technology evangelistat Oracle in the Java development tools group.About the Contributing AuthorNeil Griffin represents Liferay on the JSR 314(JSF 2.0) expert group and has 15 years of professionalexperience in software engineering. As a Liferayproject committer, Neil is responsible for interfacingwith ICEsoft in order to ensure that ICEfacesintegrates properly within Liferay Portal. Neil is thecofounder of the PortletFaces project, which makesJSF portlet development easier. He has authoredtraining classes for Liferay and ICEsoft and hasserved as a consultant for clients implementingJSF and ICEfaces portlets.
JavaServer Faces 2.0:The Complete Reference Ed Burns Chris Schalk with Neil Grifﬁn New York Chicago San Francisco Lisbon London Madrid Mexico City Milan New Delhi San Juan Seoul Singapore Sydney Toronto
To Amy, my best friend, partner, and wife. Thank you for helping me achieve my dreams. —Ed Burns For my dad, Frank, the coolest engineer/rocket scientist/cold warrior there ever was! As you used to say, “If you’re going to do something, do it with Audace!” —Chris Schalk To my beloved wife Liz,and to my dear children, Pauly and Anna. —Neil Griffin
AcknowledgmentsJ avaServer Faces is a foundation technology that builds on top of many other layers of software technology. Like any foundation software product, it is the result of the hard work and dedication of many individuals and organizations over many years of time.It is the same way with books that document such technologies, and I’d like to take theopportunity to thank some of the people who helped make this book, and JavaServer Facesitself, possible. In a world where more and more information is available only online, and much of thatinformation is coming from self-published individuals, I want to say that the publishingsystem is still the best way to deliver high-quality useful information in a portable and easilydigestible way. A Web reference is no substitute for a dog-eared, marked-up, and well-wornbook. After working with the publishing team at McGraw-Hill, I know why this is so.Our editor, Herb Schildt, has been my mentor as well as providing sure guidance as I mademy way through this large book. Thanks, Herb, for your veteran insights. Acquisitionscoordinator Joya Anthony did a great job keeping together all the disparate parts of the book.McGraw-Hill editorial director Wendy Rinaldi went through plenty of ups and downs onthis project but never lost confidence; I am proud to deliver this book for her. Thanks to copyeditor Robert Campbell and project manager Smita Rajan. To my wonderful wife, Amy. Thank you for your understanding and patience as I spentall this time on this book; you picked up the slack in our family big-time. I could not havedone it without your help and commitment. Thanks also to my sons, Owen and Logan, forunderstanding why Daddy was away all that time. I need to thank those who brought me to, worked on, and helped complete JSF. Naturally,JSF is a JCP project, so the expert group deserves prominent mention. Key members of theJSF 2.0 expert group, in alphabetical order, include Dan Allen, Keith Donald, Mike Freedman,David Geary, Ted Goddard, Jeremy Grelle, Roger Keays, Gavin King, Jason Lee, Ryan Lubke,Craig McClanahan, Kito Mann, Martin Marinschek, Pete Muir, Joseph Ottinger, Ken Paulsen,Andy Schwartz, Alexandr Smirnov, and Adam Winer. Not only is JSF a JCP project, it is alsoa community-driven project, and there are many people to thank who have helped JSFsucceed in the developer community. Some of these people include Lincoln Baxter III,Dennis Byrne, Çagatay Çivici, Hanspeter Dünnenberger, Alexander Jesse, Max Katz, ˘Alberto Lemos (Dr. Spock), Imre Oßwald, Hazem Saleh, Stan Silvert, Yara and ViniciusSenger, and Matthias Weßendorf. George Drapeau recommended I interview for the jobof leading the implementation team back in 2001. Thanks, George! Amy Fowler, theoriginal spec lead, profoundly influenced the success of JSF and was a joy to work with. xxiii
xxiv JavaServer Faces 2.0: The Complete Reference Jim Driscoll, Mimi Hills, Tony Ng, Sridatta Viswanath, and Barbara Louis have been supportive managers throughout the development of JSF. To my original core JSF team of Jayashri Visvanathan and Roger Kitain, I give deepest thanks. You are the soul of this project and I have never worked with a better team. Ryan Lubke, Justyna Horwat, and Jennifer Ball deserve thanks as the extended JSF implementation team. Ryan, you also deserve special thanks for your unswerving commitment to quality and innovation in continuing to lead Sun’s JSF implementation. I want to thank Jacob Hookom for his contribution to the JSF ecosystem in the form of Facelets, and his continuing creativity in establishing JSF as the best way to do AJAX. I want to extend a special thank you to Neil Griffin for his writing Chapters 15, 16, and the Appendix. Of course, I have to thank Chris Schalk for bringing me in to this project and for being a great collaborator. I know I am not the easiest person to work with at such close proximity, and I thank you for your patience and continued advocacy of the novice user and reader. Without you, there would be no book. Finally, I want to thank the unswerving support team of Mom, Dad, Brendan Burns, Lisa Lane, Diana Dean, Jeff Beckberger, Joe McCabe, and Vern Singleton. —Ed Burns Altamonte Springs, FL
xxvi JavaServer Faces 2.0: The Complete Reference Lighter shaded boxes indicate features that are entirely new in JSF 2.0. Darker shaded boxes are existing features of JSF that have had changes and enhancements in JSF 2.0. The arrangement of the boxes indicates dependencies between features. In cases where the features have dependencies, but the boxes cannot be adjacent, arrows indicate the dependencies. In the following text, the features are grouped by a subjective measure of “size” where bigger features were more difficult to design and are more important to understand than smaller ones. The categories used in the breakdown follow. Foundational Features These features were developed by the expert group specifically to enable other features in JSF 2.0; however, they are useful as features in their own right and are thus exposed in the public API. • System Events This feature provides a very fined-grained level of detail to observe and act upon the JSF runtime as it processes requests. It is described in detail in Chapter 9. • Resources This feature allows the JSF runtime to serve up static resources, such as style sheets, scripts, and images, in addition to the previously available capability to serve up JSF pages. It is introduced in Chapter 7 and described in detail in Chapter 10. • Facelets Facelets began as an open-source JSF extension that provided first-class templating and easy integration between markup and the JSF API. This made the experience of writing JSF pages easier and more maintainable. Facelets is included in the core JSF specification in version 2.0 and is described in detail in Chapter 4. Big Ticket Features These features are the main “release drivers” that add new value over the previous release of the specification. • Ajax This feature enables JSF views to communicate with the server directly from the browser without requiring a full-page refresh of the browser window. Ajax is an essential element of most production-quality Web applications currently in production. This feature is described in detail in Chapter 12. • Composite Components This feature enables creating true JSF components as aggregations of other JSF components. With this feature, it is easy to build your own custom JSF components and to refactor your existing views into reusable components, complete with listeners, attributes, and events. The feature is described in detail in Chapter 11. • Partial State Saving One of the biggest complaints against JSF has been the amount of memory it consumes to maintain view state between requests. This feature dramatically reduces the amount of memory for this purpose, as well as greatly simplifying the API for handling state when developing custom components. This feature is described in detail in Chapter 11.
Introduction xxvii • View Parameters Another big complaint against JSF is its insistence on using POST for all inter-page navigations. This feature is described in detail in Chapter 6.Medium-Sized FeaturesThese features are of interest to advanced JSF developers and also add value over the previousrelease, but are not as large in scope as the Big Ticket Features. • Navigation Enhancements JSF 2.0 bring several enhancements to navigation, including bookmarkability, navigation without XML navigation rules, conditional navigation, support for the POST-REDIRECT-GET pattern, the flash, and runtime inspection of navigation rules. These features are described in Chapter 6. • Exception Handling JSF 2.0 now has a central ExceptionHandler through which all exceptions are funneled. This enables easily constructing an error page that uses JSF components. This feature is described in detail in Chapter 10. • Expression Language Enhancements Several new implicit objects have been introduced, and the EL now supports method invocation on arbitrary Java methods, including parameter passing. This feature is described in detail in Chapter 5. • Validation An entirely new Java specification has been developed to address validation, JSR-303 Bean Validation. This specification integrates well with JSF 2.0 and is described completely in Chapter 8. • New Scopes In addition to the flash scope described in Chapter 5, JSF 2.0 also provides a mechanism for defining custom scopes. This is described in Chapter 13.Small New FeaturesThese features are mainly bug fixes that were too big to do in a minor revision of thespecification. • Access to the FacesContext is now available during application startup and shutdown. This feature is used in Chapter 10. • The UISelectItems child of components that extend from UISelectOne and UISelectMany can now refer to arbitrary collections of Objects. • JSF now allows the developer to tell the runtime in what phase of the software development lifecycle the runtime is executing. This “ProjectStage” feature enables the runtime to output more informative error messages and hints as the project is being iteratively developed. This feature is used in Chapter 13. • Annotations may obviate the need for XML. For nearly every XML element that can reside in a faces-config.xml file, there is now a Java language annotation that can be used in its place. This annotation feature, combined with the “navigation without XML navigation rules” feature, makes it possible to build JSF applications entirely without a faces-config.xml file. These annotations are described in Chapter 15.
xxviii JavaServer Faces 2.0: The Complete Reference Petite New Features These features round out the list of new features and include things that are simply small bug fixes that have been rolled into the JSF 2.0 spec release. • New methods on ExternalContext and FacesContext are described in Chapter 13. • Wrappers to aid in extending JSF via the decorator design pattern are described in Chapter 13. • The new DataModel.iterator feature is shown in Chapter 10. • There are several new context-param settings, described in detail in Chapter 15. If you are an experienced JSF user, you can use the preceding index of new features to skip straight to the new stuff. If you’re just coming to JSF for the first time, you needn’t know that the features are new in JSF 2.0, or how to migrate from previous versions. All of the new features will be presented naturally in context. Indeed, the entire book is written from the perspective that JSF 2.0 is the way that JSF was always meant to be. This book provides in-depth content on the following topics: • Tutorial content for using every aspect of JavaServer Faces technology • Complete coverage of all new features in JSF 2.0, not added as an afterthought, but written from scratch to show how to do things “the JSF 2.0 way” • A graphical index that quickly shows where to find information on all of the subsystems in JSF • JSF 2.0 tips outlining the differences in the latest version of JSF and how best to use them • Expert Group Insights that offer the rationale behind the design of the technology, giving readers a better understanding of how to use JSF in their own work • Detailed coverage on custom UI component development with numerous examples, including JSF 2.0 composite components • Complete coverage of the standard Ajax support in JSF 2.0 • Real-world influenced examples, including support for POST, REDIRECT, GET, Implicit Navigation, and bookmarkable JSF pages • A complete guide to extending the entire JSF framework in areas such as security, mobile rendering, localization, and Expression Language enhancements • A complete guide to the JSF config file by Neil Griffin, JSF 2.0 Expert Group member and Liferay Portal JSF Team leader • Complete reference and tutorial information for the specification’s Standard components
Introduction xxixYour Development EnvironmentWhile offering substantial coverage on a variety of Java- and JSF-enabled IDEs, this bookdoes not require the reader to use any IDE at all. A simple base environment consisting of • Java SE 6 • A Servlet 2.5 container such as Apache Tomcat 5.x • Apache Mavenis all that a reader will need to try out the code samples from the book. The easiestenvironment in which to try JSF 2.0 is Sun’s Glassfish Application Server, www.glassfish.org.Online Example Code ResourcesThroughout the book there are references to online code, sometimes with a URL or simplyreferred to as the “online extension.” All of the code examples in the book are available fordownload at McGraw-Hill’s Web site: www.mhprofessional.com/computingdownload. Inaddition, the book’s own Web site, www.jsfcompref.com, offers downloadable source code.
PART IThe JavaServer CHAPTER 1 Introduction toFaces Framework JavaServer Faces CHAPTER 2 Building a Simple JavaServer Faces Application CHAPTER 3 The JavaServer Faces Request Processing Lifecycle CHAPTER 4 The Facelets View Declaration Language CHAPTER 5 Managed Beans and the JSF Expression Language CHAPTER 6 The Navigation Model CHAPTER 7 The User Interface Component Model CHAPTER 8 Converting and Validating Data CHAPTER 9 The JSF Event Model
CHAPTER 1 Introduction to JavaServer Faces J avaServer Faces (JSF) has changed the way that Java-based Web applications are written. Designed to streamline the creation of user interfaces (UIs) for high-performance Java Web applications, JSF also simplifies the development process. JavaServer Faces offers an elegant solution to the key problems often associated with commercial-quality Web application development. Before beginning an in-depth examination of JSF, it is important to understand in a general way what JavaServer Faces is and why it is important. Therefore, this chapter begins our discussion of JSF by describing its history, design goals, and lifecycle. It also explains how JavaServer Faces fits into the overall Web application development process.What Is JavaServer Faces? At its core, JavaServer Faces is a standard Java framework for building user interfaces for Web applications. Most important, it simplifies the development of the user interface, which is often one of the more difficult and tedious parts of Web application development. Although it is possible to build user interfaces by using foundational Java Web technologies (such as Java servlets and JavaServer Pages) without a comprehensive framework designed for enterprise Web application development, these core technologies can often lead to a variety of development and maintenance problems. More important, by the time the developers achieve a production-quality solution, the same set of problems solved by JSF will have been solved in a nonstandard manner. This approach is known as “building an in-house framework.” JavaServer Faces avoids these problems by offering a robust, “best of breed” framework with well-established development patterns, built upon the experience of many preexisting Java Web development frameworks. JavaServer Faces was created through the Java Community Process (JCP) by a group of technology leaders, including Sun Microsystems, Oracle, Borland, BEA, and IBM, along with a collection of Java and Web experts well known in the industry. The original Java specification request for JavaServer Faces (JSR 127) was initiated in mid-2001 and reached its 1.0 milestone along with J2EE 1.4 in March 2004. 3