JSF 1.2 Components - Ian Hlavats - E-Book

JSF 1.2 Components E-Book

Ian Hlavats

0,0
34,79 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Today's web developers need powerful tools to deliver richer, faster, and smoother web experiences. JavaServer Faces includes powerful, feature-rich, Ajax-enabled UI components that provide all the functionality needed to build web applications in a Web 2.0 world. It's the perfect way to build rich, interactive, and "Web 2.0-style" Java web apps.
This book provides a comprehensive introduction to the most popular JSF components available today and demonstrate step-by-step how to build increasingly sophisticated JSF user interfaces with standard JSF, Facelets, Apache Tomahawk/Trinidad, ICEfaces, JBoss Seam, JBoss RichFaces/Ajax4jsf, and JSF 2.0 components. JSF 1.2 Components is both an excellent starting point for new JSF developers, and a great reference and “how to” guide for experienced JSF professionals.
This book progresses logically from an introduction to standard JSF HTML, and JSF Core components to advanced JSF UI development. As you move through the book, you will learn how to build composite views using Facelets tags, implement common web development tasks using Tomahawk components, and add Ajax capabilities to your JSF user interface with ICEfaces components. You will also learn how to solve the complex web application development challenges with the JBoss Seam framework. At the end of the book, you will be introduced to the new and up-coming JSF component libraries that will provide a road map of the future JSF technologies.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 345

Veröffentlichungsjahr: 2009

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

JSF 1.2 Components
Credits
Foreword
About the Author
About the Reviewers
Preface
What this book covers
What you need for this book
Conventions
Customer support
Downloading the example code for the book
Errata
Piracy
Questions
1. Standard JSF Components
An introduction to JSF
The Model-View-Controller architecture
Managed beans
The JSF Expression Language (JSF EL)
Converters and validators
Next steps
Getting input from the user
Rendering a text field
Rendering a text area
Form submission
Rendering a form
Rendering a button
Rendering a link
Rendering text
Rendering localized text
Registering a message bundle (JSF 1.1)
Registering a message bundle (JSF 1.2)
Rendering date/time information
Rendering parameterized text
Rendering labels
Rendering a validation message
Rendering all validation messages
Making selections
Rendering a checkbox
Rendering multiple checkboxes
Rendering radio buttons
Selecting one or selecting many values
Rendering a list of countries
Rendering a single-select list of options
Rendering a multiple-select list of options
Laying out components
Rendering a complex layout table
Rendering a table column
Displaying data
Rendering an HTML table
Summary
2. Facelets Components
A brief history of Java web development
Comparing Facelets and JSP
Configuring a JSF application to use Facelets
Configuring web.xml
Configuring faces-config.xml
Getting started with Facelets
Hello World Facelets
Rendering debug information
Iterating data in a Facelets page
Removing UI components and markup
Including UI components and markup
Including a header and footer
Creating the header Facelet
Creating the footer Facelet
Passing parameters from one Facelet to another
Rendering a UI composition
Including a UI composition
Declaring a UI composition
Rendering a UI component
Including a UI component
Declaring a UI component
Creating a Facelets UI composition template
A simple Facelets template
A simple Facelets template client
Another simple Facelets template client
A more complex Facelets template
Decorating the user interface
Decorating content on a Facelets page
Creating a Facelets decoration
Rendering a UI fragment
An advanced Facelets composition template
Summary
3. Apache MyFaces Tomahawk Components
Validating user input
Validating e-mail addresses
Validating a phone number with a regular expression pattern
Validating that two fields have an equal value
Managing date and time selection
Selecting a date
Rendering a simple calendar
Rendering an appointment schedule
File management
Uploading a file
Working with trees
Creating a tree
Creating a tree column
Customizing the tree component
Navigation menus
Creating a navigation menu
Creating bookmarkable navigation menus
Populating a navigation menu
Generating dynamic navigation menus
Using the JSCookMenu component
User interface security
Configuring web.xml
Security-enabled components
Tomahawk SecurityContext EL extension
Displaying data
Rendering an unordered list
Rendering a definition list
Rendering a data table
Paginating a data table
Rendering a multi-column data table with a newspaper layout
Summary
4. Apache MyFaces Trinidad Components
Installation and Configuration
What is Ajax?
Receiving input from the user
Rendering a color picker
Rendering a calendar
Rendering a number spinbox
Rendering a text field
Rendering a selectable list of values
Client-side conversion and validation
Enabling client-side validation in trinidad-config.xml
Validating one field at a time
Enabling Ajax functionality
Partial submit and partial triggers
Polling the server
Rendering a status indicator
Rendering a progress bar
Laying out components on the screen
Rendering a row layout
Rendering a complex table layout
Rendering a form layout
Rendering a panel group layout
Shuttling selections between lists
Rendering a multiple selection shuttle
Rendering an ordered shuttle
Working with tree and tree table components
Rendering a tree
Rendering a tree table
Creating navigation menus
Rendering a navigation tree
Rendering breadcrumbs
Rendering a multistep process (Train)
Rendering a process choice bar
Skinning and theme selection
Creating a new Trinidad skin
Implementing the skin's cascading style sheet
Rendering an icon
Customizing the Trinidad tree component's node icons
Implementing dialog windows
Declaring dialog navigation rules in faces-config.xml
Launching a dialog window
Returning a value from a dialog window
Summary
5. ICEfaces Components
Receiving input from users
Rendering validation messages and text with effects
Receiving HTML input from users
Handling file uploads with ICEfaces
Rendering a calendar component
Creating navigation and pop-up menus
Creating a horizontal navigation menu with submenus
Rendering a vertical navigation menu with submenus
Adding menu separator items
Using context menus
Using tree components
Using the default tree node icons
Using custom tree node icons
Displaying data in tables
The ICEfaces data table component
Rendering dynamic columns
Implementing sortable column headers
Supporting resizable columns
Data table single row selection mode
Data table multiple row selection mode
Data table enhanced multiple row selection mode
Implementing data set paging
Rendering charts
Rendering a stacked bar chart
Rendering a 3-D pie chart
Rendering a bar chart
Laying out components with panels
Working with a border layout
Rearranging elements in a list
Rendering a series of components
Rendering collapsible panels
Creating a tabbed user interface
Working with modal dialogs
Rendering a simple modal dialog
Rendering a draggable dialog box
Rendering a draggable modal dialog
Summary
6. JBoss Seam Components
Introducing the JBoss Seam framework
Java Enterprise Edition (Java EE) technology
Understanding Java SE and Java EE
Introducing Enterprise JavaBeans (EJB3) technology
Introducing the Java Persistence API (JPA)
Container Managed Transactions (CMT)
Activation and passivation for Stateful Session Beans (SFSBs)
Object pooling for Stateless Session Beans (SLSBs)
Integrating EJB3 and JSF with Seam
Introducing Seam components
Introducing REST
Next steps
Validating user input with the Seam framework
Implementing JSF validation with Seam
JPA and the Hibernate Validator framework
Decorating the UI to improve form validation
Adding cutting-edge Ajax technology with Ajax4jsf
Displaying success messages in JSF
Seam conversation management
Temporary conversations
ShippingCalculatorBean.java
faces-config.xml
pages.xml
conversation01.jsf
conversation02.jsf
Starting a long-running conversation
Declaring navigation rules in faces-config.xml
Defining a long-running conversation in pages.xml
Implementing OrderBeanImpl.java
The introductory page of the order process
The customer registration screen (Step 1)
The shipping information screen (Step 2)
The order details confirmation screen (Step 3)
Concurrent conversations
Debugging Seam applications
Summary
7. JBoss RichFaces and Ajax4jsf Components
Introducing JBoss RichFaces and Ajax4jsf
The JBoss RichFaces component library
The Ajax4jsf component library
Accepting user input
Rendering editable text
Rendering an in-place select component
Combining in-place input and select components
Rendering a slider component
Rendering a number spinner component
Rendering a calendar component
Rendering a color picker component
Rendering a combo box component
Rendering a suggestion box component with auto-complete
Rendering a pick list component
Rendering a rich text editor component
Using Ajax effectively
Understanding how Ajax4jsf works
Ajax-enabled form submission
Invoking an Ajax-enabled command link
Polling the server asynchronously
Panel components
Creating a basic panel
Rendering a panel bar
Rendering a panel menu
Rendering groups of menu items
Rendering a tabbed user interface
Rendering a toggle panel
Displaying data
Rendering a data table
Rendering a data table with a header, footer, and caption
Implementing sortable data table column headers
Filtering rows in a data table
Rendering a data grid
Adding a data scroller
Customizing the data scroller
Rendering an ordered list
Customizing an ordered list
Rendering a data definition list
Using special components
Rendering a Google Maps object
Rendering a Microsoft Virtual Earth object
Summary
A. Learning JSF: Next Steps
JSF 2.0
New JSF annotations added to ease configuration
Simplified navigation mapping convention
JSF 1.x Navigation Mapping
JSF 2.0 Navigation Mapping
A Web resource loading mechanism for images, stylesheets, JavaScript files, and so on
Facelets is now integrated in JSF 2.0
The new "composite" JSF tag library for creating composite components
Built-in support for adding Ajax capabilities to UI components with <f:ajax>
The PrimeFaces component library
Next steps
Index

JSF 1.2 Components

Ian Hlavats

JSF 1.2 Components

Copyright © 2009 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, Packt Publishing, nor its dealers or distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: November 2009

Production Reference: 2111209

Published by Packt Publishing Ltd.

32 Lincoln Road

Olton

Birmingham, B27 6PA, UK.

ISBN 978-1-847197-62-7

www.packtpub.com

Cover Image by Vinayak Chittar (<[email protected]> )

Credits

Author

Ian Hlavats

Reviewers

Cagatay Civici

Ted Goddard

Daniel Hinojosa

Kito D. Mann

Eric Mulligan

Phil Stang

Ghazala Wahid

Matthias Wessendorf

Acquisition Editor

Rashmi Phadnis

Development Editor

Swapna Verlekar

Technical Editor

Namita Sahni

Editorial Team Leader

Akshara Aware

Project Team Leader

Priya Mukherji

Project Coordinator

Prasad Rai

Proofreaders

Chris Smith

Lesley Harrison

Andie Scothern

Indexers

Monica Ajmera

Rekha Nair

Graphics

Nilesh R. Mohite

Production Coordinator

Dolly Dasilva

Cover Work

Dolly Dasilva

Foreword

In the hyper-competitive and opinionated world of Java web frameworks, the strength of the community surrounding the framework is at least as important as the quality of the technology in framework. This statement is supported by the fact that no technology is perfect, there are always omissions and bugs, and the best remedy for these imperfections and flaws is a vibrant developer community from which everyone can pull ideas, workarounds, and help. I've long known of Ian Hlavats and his JSF Toolbox product but finally had the pleasure of meeting him in September 2008 at the first annual North American JavaServer Faces Developer conference. Ian's JSF Toolbox is the realization of one of the core ideas of JavaServer Faces: it takes a team of individuals with varying skills and expertise to build enterprise software, and not everyone on the team is an Object-oriented software developer. In fact, the great majority of the talented web designers practicing today use Adobe Dreamweaver as their workhorse tool. Bringing the power of JavaServer Faces to these users is very important to the success of JSF, and therefore, very important to me.

Just as Ian's tool builds on a core idea of JSF, so does his book: that of the power and centrality of UI components. In this book you'll find a detailed treatment of the most popular JSF component libraries in use as of this writing. Mastering the use of these components is just as important as mastery of the core JSF technology on which they are built. From his vantage point as the developer of JSF Toolbox, and the leader of the successful JSF consulting company Tarantula Consulting, Ian is very well placed to understand how JSF components are used in practice. Complementing this understanding is his sure skill in explaining their use in clear, easy-to-follow prose. I'm sure you'll find this book a valuable addition to your JSF toolbox.

Ed Burns

JavaServer Faces Specification Lead and Expert Group Member

Altamonte Springs 2009

About the Author

Ian Hlavats is an experienced Java developer, architect, consultant, and instructor specializing in JavaServer Faces (JSF). He has successfully designed, implemented, and released many JSF applications. One of his accomplishments is the creation of JSFToolbox for Dreamweaver, a suite of JSF UI development tools, which is now used by Fortune 500 companies and government agencies worldwide.

Ian has been teaching Java programming at the college level and in corporate training environments for several years. Ian was an invited speaker at the JSFOne conference in 2008 where he delivered a presentation on building JSF applications alongside a panel of other JSF industry experts. Ian was also invited to deliver presentations on hands-on JSF design and development using JSF tools such as Eclipse, NetBeans, and Adobe Dreamweaver at the JSF Summit conference in Orlando, Florida in December 2009.

Ian has been working professionally as a Java consultant and Java instructor since 2003. His first project was an internal audit project tracking system for the Government of Canada that was implemented using the Struts, Spring, and Hibernate frameworks, and a MySQL database.

After working extensively with Struts, Ian became very interested in JSF since it solved many issues that Struts did not address. Ian's involvement in the JSF community began around 2005 when he was active on JSF mailing lists, providing feedback and submitting bug reports to the JSF and Facelets development teams. While Ian was employed in the Government, he was also teaching Java courses at the Algonquin College in Ottawa.

Ian left his permanent job in the Government in 2006 to work for his own company, Tarantula Consulting Inc., and pursued Java development contracts with high tech startups and small businesses in the Ottawa area. He worked extensively with JSF and in the process he developed a suite of JSF extensions for Adobe Dreamweaver. JSFToolbox for Dreamweaver was released in 2006 and has since expanded its support for JSF to include new extensions for Facelets, Apache MyFaces Tomahawk, Apache MyFaces Trinidad, ICEfaces, JBoss Seam, and JBoss RichFaces/Ajax4jsf.

From 2007 to 2008, Ian worked as a Java instructor delivering Java training to software architects, engineers, and managers at Cognos/IBM. During this time, he also won a contract to consult on an enterprise Java application for the Government of Canada. Ian conducted an architectural assessment of an existing Java EE application, performed extensive code review, interviewed staff, coordinated with other consultants, prepared a report, implemented his recommendations to improve the Java application architecture, and trained Java development staff. Tarantula Consulting continues to work on JSF projects for high tech startup companies in Canada and the US.

In his spare time, Ian enjoys playing flamenco guitar and taking road trips on a Harley-Davidson motorcycle.

Ian is currently working on a second book on writing custom JSF components.

I would like to extend my sincere gratitude to all the technical reviewers who participated in this project. It means a great deal to me that so many experts and esteemed colleagues in the JSF community would take the time to help me improve this book. I would also like to thank my Java students for all their help over the past two years on my many Java projects. I would also like to thank my partner Helene for all her support and for the endless cups of coffee.

About the Reviewers

Cagatay Civici is the PMC member of open source JSF implementation Apache MyFaces and the project leader of popular PrimeFaces framework. In addition to being a recognized speaker in international conferences such as JSFSummit, JSFDays and local events, he's an author and technical reviewer of books regarding web application development with Java and JSF. Cagatay is currently working as a consultant and instructor in the UK.

Ted Goddard is the Chief Software Architect at ICEsoft Technologies and is the technical leader for the JavaServer Faces Ajax framework, ICEfaces. Following a PhD in Mathematics from Emory University that answered open problems in complexity theory and infinite colorings for ordered sets, he progressed to post-doctoral research in component and web-based collaborative technologies. He has held positions at Sun Microsystems, AudeSi Technologies, and Wind River Systems, and currently participates in the Servlet and JavaServer Faces expert groups.

Daniel ("Danno") Hinojosa is a self-employed consultant from Albuquerque, New Mexico who specializes in development, teaching, and speaking. Danno has been developing enterprise solutions for commercial and government entities since 1999. His primary consulting focus is the design of well-tested web and desktop applications using Java and Groovy. Danno teaches Java, Groovy, Ajax, Automated Testing, XML, and software testing at the University of New Mexico Continuing Education. He is also a co-founder of the Albuquerque Java Users Group. Danno has reviewed a number of books: Seam In Action, Hibernate Search In Action, and Programming Scala.

Kito D. Mann is editor-in-chief of JSF Central (www.jsfcentral.com) and the author of JavaServer Faces in Action (Manning). He is a member of several Java Community Process expert groups (including JSF and Portlets), and Principal Consultant at Virtua, Inc., specializing in enterprise application architecture, training, development, mentoring, and JSF product strategy. Kito has consulted with several Fortune 500 clients, including Prudential Financial and J.P. Morgan Chase & Company, and was recently the chief architect of an educational application service provider. He holds a BA in Computer Science from Johns Hopkins University.

Eric Mulligan is a certified Enterprise Java Developer who studied Java programming with Ian Hlavats. He was employed as a Java developer with Ian's company, Tarantula Consulting Inc., for almost a year on various projects including the JSFToolbox for Dreamweaver suite of extensions.

Phil Stang has been in software development for more than 20 years and has been working with Java since Java 1.01 release. He has developed and led software development teams in the financial, aerospace, and telecom sectors, as well as federal policing. He has been teaching Java since 1997. His hobbies include skiing, windsurfing, and flying model aircrafts competitively.

Ghazala Wahid has more than four years of experience as a Software and Reports Developer. She is a Sun Certified Java Programmer as well as a Sun Certified Web Component Developer.

Matthias Wessendorf is a principal software developer at Oracle. He currently works on server-side-push support for ADF Faces and Trinidad 2.0. Matthias also contributes to the OpenSource community, mainly Apache MyFaces and Apache MyFaces Trinidad. Follow Matthias on Twitter (@mwessendorf).

Preface

Java developers and Web designers today need more powerful tools to deliver the richer, faster, and smoother web experience that users now demand. JavaServer Faces is an advanced web application framework that includes hundreds of powerful, feature-rich, Ajax-enabled UI components that provide all of the functionality needed to build web applications in a Web 2.0 world.

There has never been a better time to learn JSF. The JSF ecosystem is growing fast and the abundance of JSF components, development tools, industry conferences, and job opportunities is impressive. Learning JSF can be a challenge, but this book makes it easy by showing you the most important JSF technologies and concepts that you need to know to become a JSF professional.

What this book covers

Chapter 1:Standard JSF Components introduces you to the JavaServer Faces framework and the key concepts that you need to understand to build simple JSF applications. You will learn about Model-View-Controller, managed beans, the JSF expression language, converters, and validators. You will also discover how to use the standard JSF user interface components (such as text fields, radio buttons, selection lists, and checkboxes) to receive text, date/time, numeric, and other types of input from users as well as handle form submission, render messages, lay out components in a grid, and display a data table.

Chapter 2:Facelets Components introduces the Facelets view definition framework and compares it to JSP as the view technology for JSF. You will learn about working with valid XHTML documents and will see examples of how to use the Facelets framework to create simple and complex composite user interfaces based on Facelets templates. You will also learn how to use the Facelets component library to display debugging information, iterate data, include and remove UI components and markup, pass parameters between Facelets pages, create reusable view elements, and apply advanced Facelets templating concepts.

Chapter 3:Apache MyFaces Tomahawk Components covers the Apache MyFaces Tomahawk component library and looks at how to use Tomahawk components such as calendars, trees, a file upload component, and navigation menus to solve common web development tasks. You will learn how to use Tomahawk components to validate user input, accept date/time input, upload files, render tree components, create navigation menus, implement user interface security, display sortable data tables, and use newspaper layouts.

Chapter 4:Apache MyFaces Trinidad Components discusses the Apache MyFaces Trinidad framework and Ajax technology and will introduce you to many of the 100 plus rich user interface controls in this powerful component library. You will learn how to use color choosers, pop-up calendars, dynamic trees, data tables, a number spinbox, shuttle components, navigation menus, layout panels, and more, to implement typical web development use cases. You will also learn how to use the Apache MyFaces Trinidad dialog framework to add dialog windows to your application, how to enable Trinidad's client-side JavaScript validation, how to create dynamic navigation menus, how to design custom skins and icons for Trinidad's skinning framework, and how to use Trinidad's partial page rendering (PPR) Ajax feature to enhance your JSF pages.

Chapter 5:ICEfaces Components introduces the ICEfaces Ajax component library, and explains many of the important concepts that you need to know in order to develop JSF applications based on ICEfaces. You will learn how to use many of the more than 50 Ajax-enabled user interface components in the ICEfaces component library, such as how to add dynamic effects to your pages to enhance input validation, how to use navigation and context menus, how to work with tree components, how to render dynamic data tables that support sorting and paging, how to render pie charts and bar graphs, how to create a tabbed user interface, how to arrange elements using drag-and-drop, how to lay out components in a grid, and how to work with modal dialogs.

Chapter 6:JBoss Seam Components covers the JBoss Seam framework and introduces you to the fundamentals of building JSF applications that use the full Java Enterprise Edition (Java EE) technology stack. You will learn how to configure Seam, how to apply Seam annotations to Java classes, and how to use Seam JSF controls to bridge the gap between Enterprise JavaBeans (EJB3) components, the Java Persistence API (JPA), and the JSF framework. This chapter will show you how to validate user input efficiently using Seam, JPA, and the Hibernate Validator framework. You will also discover how to use the Seam tag library and Java API to display validation and success messages, render required field decorations, display debugging information, use Seam's conversation management feature to implement robust JSF workflows, and how to combine Seam with JBoss RichFaces and Ajax4jsf to build next generation JSF applications.

Chapter 7:JBoss RichFaces and Ajax4jsf Components covers the JBoss RichFaces and Ajax4jsf component libraries. You will learn how to use many advanced RichFaces components such as in-place editable text, a calendar, an Ajax-based auto-complete suggestion box, rich panel and menu components, a Google map component, a Microsoft Virtual Earth component, dynamic data tables with sorting and paging, data grids, a color picker, a slider component, a number spinner, a picklist control, a rich text editor, and more. You will also learn how to add Ajax support to non-Ajax JSF components with Ajax4jsf, and how to perform advanced Ajax tasks such as submitting forms asynchronously, submitting one component at a time, polling the server, and re-rendering parts of the page after an Ajax request.

Appendix:Learning JSF: Next Steps introduces JavaServer Faces 2.0 and provides a summary of the key features in the next generation of the JSF framework. You will discover how JSF 2.0 emphasizes convention over configuration by learning about the new JSF annotations to simplify managed bean configuration and reduce XML, the new JSF resource loading mechanism, the simplified navigation mapping convention, the integration of Facelets into the core JSF framework, the new "composite" JSF tag library for defining composite components, and the significantly improved support for Ajax that is now built-in to the framework. You will also learn about PrimeFaces, a promising new JSF component library.

What you need for this book

To run the example applications included with this book, you will need a Java Servlet/JSP container that supports JSF 1.2 such as Apache Tomcat 6.0 (http://tomcat.apache.org) and a Java EE container such as JBoss Application Server 4.2 (http://www.jboss.org).

The example applications were developed using Eclipse IDE for Java EE Developers (Galileo Release) (http://www.eclipse.org), Adobe Dreamweaver CS4 (http://www.adobe.com), and JSFToolbox for Dreamweaver 3.5 (http://www.jsftoolbox.com). You will also need the MySQL 5.1 database (http://www.mysql.org). The example applications can be downloaded from the publisher's website (http://www.packtpub.com).

Conventions

In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

Code words in text are shown as follows: "The following example demonstrates some of the context parameters that we set in web.xml to enable the Facelets ViewHandler."

A block of code will be set as follows:

<application> <message-bundle>messages</message-bundle> <locale-config> <default-locale>en</default-locale> <supported-locale>fr</supported-locale> <supported-locale>es</supported-locale> </locale-config> </application>

When we wish to draw your attention to a particular part of a code block, the relevant lines or items will be shown in bold:

<h:inputText id="emailAddress" value="#{customerBean.customer.emailAddress}" required="#{true}"> <t:validateEmail message="The email address you have entered is not valid." /> </h:inputText>

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in our text like this: "First let's examine the code for the Cancel button."

Note

Warnings or important notes appear in a box like this.

Note

Tips and tricks appear like this.

Feedback from our readers is always welcome. Let us know what you think about this book —what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply drop an email to <[email protected]>, and mention the book title in the subject of your message.

If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or email <[email protected]>.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code for the book

Note

Visithttp://www.packtpub.com/files/code/7627_Code.zip to directly download the example code.

Errata

Although we have taken every care to ensure the accuracy of our contents, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in text or code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration, and help us to improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the let us know link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata added to any list of existing errata. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Piracy

Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors, and our ability to bring you valuable content.

Questions

You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.

Chapter 1. Standard JSF Components

The components and examples covered in this chapter have been selected to introduce a number of important concepts for developing JSF user interfaces. It is necessary to understand the basic JSF components because they are the building blocks from which other components and component libraries are derived.

We will begin by looking at a number of common web application development tasks and how they can be implemented using standard JSF components. In the process, we will learn how to use other JSF artifacts, such as managed beans, converters, validators, and more.

An introduction to JSF

While the main focus of this book is learning how to use JSF UI components, and not to cover the JSF framework in complete detail, a basic understanding of fundamental JSF concepts is required before we can proceed. Therefore, by way of introduction, let's look at a few of the building blocks of JSF applications: the Model-View-Controller architecture, managed beans, EL expressions, converters, and validators.

The Model-View-Controller architecture

JSF is based on the Model-View-Controller (MVC) architecture. The Model in MVC represents the data of the application, and is typically implemented using Plain Old Java Objects (POJOs) based on the JavaBeans API. The View in MVC represents the user interface of the application and is responsible for rendering data and user interface controls to the user. The Controller in MVC represents an object that responds to user interface events and deals with querying or modifying the Model.

Managed beans

Managed beans are the Controllers of a JSF application, handling events in the user interface and updating the Model in response to user interaction. A managed bean is simply a Java class with instance variables and methods that are coupled to the application's domain model and to JSF's event handling API.

The JSF Expression Language (JSF EL)

The JSF Expression Language (JSF EL) is a simple, powerful, object-oriented, and typesafe scripting language used to bind UI components to managed bean properties and methods. The following example shows how to display a customized welcome message that references a backing bean property using the JSF EL:

<h:outputText value="Hello, #{backingBean.username}" />

Converters and validators

JSF includes standard converters for common data types such as numbers, Boolean values, and dates, and also supports custom converters for handling user-defined data types. Additionally, JSF includes standard validators for typical input validation scenarios such as checking required fields and numbers, and also supports custom validators. We will see a number of both, standard converters and validators and custom convertors and validators, throughout this book.

Next steps

Now that we have introduced the Model-View-Controller pattern, managed beans, the JSF Expression Language, and converters and validators, we are ready for a more in-depth discussion on how to use JSF UI components effectively to perform common web development tasks. Specifically, we will look at the following use cases:

Getting input from the userForm submissionRendering textMaking selectionsLaying out componentsDisplaying tabular data

Getting input from the user

Accepting input from a user is one of the most common scenarios for web application developers. User input is typically character data that represents different types of information, such as dates, numbers, and text. JSF includes a number of standard components that represent HTML form elements that can be used to collect this information from users.

The HtmlInputText component, for example, is a good choice for accepting short textual input from the user. For use cases that require more text, such as a memo field or comment box, the HtmlInputTextarea component is a better choice as it can accommodate multiline text entry more easily.

Rendering a text field

The following example demonstrates how to accept text input from the user:

<f:view> <h:form> <div> <h:outputLabel for="name" value="Enter your name: " /> <h:inputText id="name" value="#{backingBean.name}" /> <h:commandButton value="Submit" /> </div> <div> <h:outputText value="Hello, #{backingBean.name}" rendered="#{backingBean.name ne null and backingBean.name ne ''}" /> </div> </h:form> </f:view>

Notice the value attribute of the<h:inputText> tag. The text field is bound to a backing bean String property using the JSF Expression Language (JSF EL). When the form is submitted, the property is set to the value of the text entered by the user.

This example also demonstrates conditional rendering of JSF components. Most JSF tags support the rendered attribute. This attribute allows us to control when a JSF component should be displayed on the page. In this case, the<h:outputText> tag is conditionally rendered when the backing bean's name property is not null and is not equal to an empty string.

In the next example we will use a text field to receive a date value from the user. First we register the standard JSF date time converter on the UI component by nesting the<f:convertDateTime> tag inside the<h:inputText> tag. This converter will attempt to convert the text entered by the user to a date by using the conversion pattern specified in the pattern attribute. Next we register a custom date validator to make sure that the converted date value represents a valid birth date. The error message rendered below the text field was produced by our validator class.

<f:view> <h:form> <div> <h:outputLabel for="name" value="Enter your birthdate (M/d/yyyy): " /> <h:inputText id="name" value="#{backingBean.date}"> <f:convertDateTime type="date" pattern="M/d/yyyy" /> <f:validator validatorId="customDateValidator" /> </h:inputText> <h:commandButton value="Submit" /> </div> <h:message for="name" style="display:block" errorStyle="color:red" /> <div> <h:outputText value="You were born on " rendered="#{backingBean.date ne null}" /> <h:outputText value="#{backingBean.date}"> <f:convertDateTime type="date" dateStyle="full" /> </h:outputText> </div> </h:form> </f:view>

The following screenshots demonstrate a custom date validator class that determines if a date represents a valid birth date. The error message rendered below the text field was produced by our validator class.

When the validation is successful, our backing bean property is updated and the view is rendered again in the browser. This time, our conditionally rendered message is displayed to the user.

The next example shows how to accept numeric input from the user. JSF includes built-in converter classes that handle conversions between character data (strings) and Java data types, such as Integer, Boolean, Float, Long, and so on. In this example, we specify that the text field component can only accept a whole number between 20 and 50 by using the<f:validateLongRange> tag to register a standard validator on the component.

<h:inputText id="number" value="#{backingBean.number}"> <f:validateLongRange minimum="20" maximum="50" /> </h:inputText>

Note that the error message below the text field was produced by the built-in JSF NumberConverter class and is the default text for this particular error. We can override the default JSF conversion and validation error messages by declaring messages with the same keys in our resource bundle.

If we enter a non-numeric value, we will receive an appropriate error message:

If the number is not in the specified range, we will also get an error:

Tip

JSF validation messages

The JSF framework includes predefined validation messages for different validation scenarios. These messages are defined in a message bundle (properties file) including the JSF implementation JAR file. Many of these messages are parameterized, meaning that as of JSF 1.2, a UI component's label attribute value can be inserted into these messages; the default JSF validation messages can be overridden by specifying the same message bundle keys in the application's message bundle.

Finally, the value is accepted by the converter and our view is updated, displaying another conditionally rendered HtmlOutputText component.

Rendering a text area

The HtmlInputTextarea component is identical to the HtmlInputText component, except that it can specify rows and cols attributes to control the width and height of the text area.

<h:inputTextarea rows="10" cols="80" value="#{backingBean.description}" />

Form submission

When the user clicks on a button or a link with JavaScript enabled, the browser collects the HTML form data and submits it to the web server for processing. It is important to note that web pages may contain multiple forms, provided that the forms are not nested. Also, typically the browser can only submit one form at a time. (We will look at how to use Ajax to submit multiple forms at the same time, later in this book.) Therefore, any UI components that should have their values included in the JSF lifecycle for a particular request should be contained within the same form. In this section, we will look at common ways to submit an HTML form using JSF components.

The standard JSF HTML component library includes components that can be used to render and submit an HTML form. Any components within the form are included in the form submission and will have their user input values sent to the server, converted, and validated during the JSF request processing lifecycle.

Rendering a form

To display a form on a JSF page, you can use the<h:form> tag. This tag renders a UIForm component as an HTML form using the default HTML RenderKit. This produces an HTML form tag at request time. In JSF, we should always use the<h:form> tag and not the actual HTML form tag to render a form because the JSF<h:form> tag renders additional hidden form fields containing important information about the UI component tree for the current view.

The<h:form> tag component is very common in JSF views, as almost all components need to be included in a form in order to be functional. A JSF view may contain several forms, and in general it is a good idea to divide your user interface into separate forms when it can accept different types of unrelated information from the user.

A good example is a JSF view that has a page header with a user sign-in form, and a content area with a user feedback form. The UI components and bindings involved in authentication have nothing to do with the components and bindings involved in gathering feedback from the user, so these two groups of components should be organized into separate forms. In JSF, all the components in a form are updated when that form is submitted. Therefore, we want to group related controls together and isolate them from groups of other, unrelated controls.

Before an HTML form can be submitted, the user must click on or invoke a user interface component that has been designated as a form submission component. Typically, this is an HTML input element of the type submit or image rendered as a button or an image in the browser, but using JavaScript it can also be a hyperlink, checkbox, radio button, select menu, or any other visible or non-visible element on the page.

To begin with a simple example, let's look at how to submit a form using a button or a link component. The standard JSF component library includes two components that are commonly used to submit a form. The HtmlCommandButton component is rendered as a submit button by the<h:commandButton> tag, and the HtmlCommandLink component is rendered as a hyperlink by the<h:commandLink> tag.

Rendering a button

The<h:commandButton> tag should have at least a label value. In this example, the component simply submits the form when it is invoked, and nothing else.

<h:commandButton value="Submit" />

The HtmlCommandButton component can also invoke our application logic when it is pressed. The component in this example now submits the form and, if conversion and validation are successful, it then calls a method in our backing bean. This is achieved by specifying a method expression for the button using the JSF EL. We can "wire" several HtmlCommandButton components to different methods in our backing bean.

<h:commandButton value="Add" actionListener="#{backingBean.addWord}" /> <h:commandButton value="Remove" actionListener="#{backingBean.removeWord}" />

The Java method in our BackingBean class would be implemented as follows:

public void removeWord(ActionEvent event) { words.remove(word); }

In this example, we can add to or remove words from a collection of words that is stored in our backing bean using a simple JSF user interface.

Rendering a link

The<h:commandLink> tag is similar to the<h:commandButton> tag. The value attribute also specifies the label, and both the tags have an actionListener attribute that registers a backing bean method on the component using a JSF EL method expression.

<h:commandLink value="Add" actionListener="#{backingBean.addWord}" /> <h:outputText value=" | " /> <h:commandLink value="Remove" actionListener="#{backingBean.removeWord}" />

The same screen continues to function in exactly the same way after we replace our command buttons with command links.

Rendering text

Another common task for web applications is to render text in the browser. The HTML markup language includes a number of elements that can be used to render text. JSF includes standard components that represent these HTML elements and extend their capabilities to include support for internationalization, conditional rendering, formatted text, validation messages, and more.

Many elements in HTML, such as<p>, <div>, <span>, and<label> for example, can be used to render text. The JSF<h:outputText> tag renders the HtmlOutputText component as an arbitrary text value or as a<span> element that contains text if CSS attributes on the tag are set. The<h:outputText> can be used to render plain text or HTML that originates from the backing bean.

The value attribute of the tag specifies the text to be rendered. If we are rendering HTML, we should make sure to set the escape attribute to false so that the HTML is rendered properly in the browser. The<h:outputText> tag can also be used to render arbitrary Java objects, such as Date, Integer, Float, and other types. When the value attribute contains an EL expression that evaluates to a Java type other than String, the component attempts to render the value as a string. If a converter is registered on the component, the converter is responsible for converting the object to a string.

One of the uses of the HtmlOutputText component is to display localized messages. Let's look at a few examples of how to use this component to internationalize our JSF pages. In the process, we will have the opportunity to look at the JSF framework's internationalization support in more detail.

Rendering localized text