JSF 2.0 Cookbook - Leonard Anghel - E-Book

JSF 2.0 Cookbook E-Book

Anghel Leonard

0,0
23,50 €

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

In Detail

JavaServer Faces is a Java-based Web application framework intended to simplify development of user interfaces for Java EE applications. You may already be aware of the laborious search through reference guides and documentation to develop your JSF applications. With the JSF Cookbook, you can find solutions to the most common JSF problems in a quick and easy way.

This book will cover all the important aspects involved in developing JSF applications. It provides clear instructions for getting the most out of JSF and offers many exercises to build impressive desktop-style interfaces for your web applications. Develop JSF applications starting with simple recipes and gradually moving on to complex recipes.

We discuss all of the fundamental aspects of JSF applications. Once you locate your desired topic, you can try to find a recipe that corresponds to your problem.

We start off with the simple concepts of Converters, validators and file management. We then work our way with various resources such as CSS, JavaScript, and images to improve your web applications. You will learn to build simple and complex custom components to suit your needs. Next, you get to exploit AJAX as well as implement internationalization and localization for your JSF applications. We then look into ensuring security for your applications and perform testing of your applications. You also get to learn all about Facelets and explore the newest JSF 2.0 features. Finally you get learn a few integrations such as JSTL with JSF, Spring with JSF, and Hibernate with JSF. All these concepts are presented in the form of easy-to-follow recipes.

Each chapter discusses separate types of recipes and they are presented with an increasing level of complexity from simple to advanced. All of these recipes can be used with JSF 1.2 as well.

This book helps you to find solutions to the most common aspects regarding JSF development with clear and easy-to-follow recipes

Approach

The JSF 2.0 Cookbook contains step-by-step instructions for JSF users to build desktop-style interfaces in their own web applications. The book is designed so that you can refer to it chapter by chapter, or you can look at the list of recipes and read them in no particular order.

Who this book is for

This book is for two types of audience:

  • Newcomers who know the basics of JSF but are yet to develop real JSF applications.
  • JSF developers who have previous experience but are lacking best practices and a standard way of implementing functionality

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 373

Veröffentlichungsjahr: 2010

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 2.0 Cookbook
Credits
About the Author
About the Reviewer
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Errata
Piracy
Questions
1. Using Standard and Custom Converters in JSF
Introduction
Working with implicit and explicit conversions
Getting ready
How to do it...
How it works...
There's more...
See also
Standard converters for numbers
Getting ready
How to do it...
How it works...
There's more...
See also
Standard converters for date and time
Getting ready
How to do it...
See also
Converters and NULL values
Getting ready
How to do it...
How it works...
See also
Creating and using a custom converter
Getting ready
How to do it...
How it works...
There's more...
See also
Using custom converters for h:selectOneMenu
Getting ready
How to do it...
How it works...
There's more...
See also
Binding converters to backing bean properties
Getting ready
How to do it...
How it works...
See also
RichFaces and standard converters
Getting ready
How to do it...
How it works...
See also
RichFaces and custom converters
Getting ready
How to do it...
How it works...
See also
Instance variables in converters
Getting ready
How to do it...
How it works...
See also
Client-side converters with MyFaces Trinidad
Getting ready
How to do it...
How it works...
There's more...
See also
2. Using Standard and Custom Validators in JSF
Introduction
Using a standard validator
Getting ready
How to do it...
How it works...
See also
Customizing error messages for validators
Getting ready
How to do it...
How it works...
There's more...
See also
Creating a custom validator
Getting ready
How to do it...
How it works...
There's more...
See also
Binding validators to backing bean properties
Getting ready
How to do it...
How it works...
See also
Validating forms with RichFaces rich:beanValidator
Getting ready
How to do it...
How it works...
There's more...
See also
Validating forms with RichFaces rich:ajaxValidator
Getting ready
How to do it...
How it works...
See also
Apache MyFaces Commons validators
Getting ready
How to do it...
How it works...
See also
Bean validation with f:validateBean
Getting ready
How to do it...
There's more...
How it works...
See also
Enforcing a value's presence with f:validateRequired
Getting ready
How to do it...
How it works...
See also
Using regular expressions with f:validateRegex
Getting ready
How to do it...
How it works...
See also
3. File Management
Introduction
Downloading files using Mojarra Scales
Getting ready
How to do it...
How it works...
See also
Multi-file upload using Mojarra Scales
Getting ready
How to do it...
How it works...
See also
File upload with Apache MyFaces Tomahawk
Getting ready
How to do it...
How it works...
There's more...
See also
AJAX multi-file upload with RichFaces
Getting ready
How to do it...
How it works...
There's more...
See also
Downloading with PrimeFaces 2.0
Getting ready
How to do it...
How it works...
See also
PPR multi-file upload with PrimeFaces 2.0
Getting ready
How to do it...
How it works...
See also
Extracting data from an uploaded CSV file
Getting ready
How to do it...
How it works...
See also
Exporting data to Excel, PDF, CVS, and XML
Getting ready
How to do it...
There's more...
See also
4. Security
Introduction
Working with the JSF Security project
Getting ready
How to do it...
How it works...
See also
Using the JSF Security project without JAAS Roles
Getting ready
How to do it...
How it works...
Using secured managed beans with JSF Security
Getting ready
How to do it...
See also
Using Acegi/Spring security in JSF applications
Getting ready
How to do it...
How it works...
See also
5. Custom Components
Introduction
Building a "HelloWorld" JSF custom component
Getting ready
How to do it...
How it works...
See also
Renderers/validators for custom components
Getting ready
How to do it...
How it works...
See also
Adding AJAX support to JSF custom components
Getting ready
How to do it...
Stage 1—creating an image viewer
Stage 2—transforming the image viewer into an image slide viewer
Stage 3—adding AJAX capabilities to the image slide viewer component
See also
Using Proxy Id library for dynamic IDs
Getting ready
How to do it...
How it works...
See also
Using JSF ID Generator
Getting ready
How to do it...
How it works...
See also
Accessing resources from custom components
How to do it...
How it works...
There's more...
Custom components with Archetypes for Maven
Getting ready
How to do it...
How it works...
See also
RichFaces CDK and custom components
Getting ready
How to do it...
There's more...
See also
Composite custom components with zero Java
Getting ready
How to do it...
How it works...
See also
Creating a login composite component in JSF 2.0
Getting ready
How to do it...
How it works...
See also
Building a spinner composite component in JSF 2.0
Getting ready
How to do it...
How it works...
See also
Mixing JSF and Dojo widget for custom components
Getting ready
How to do it...
See also
6. AJAX in JSF
Introduction
A first JSF 2.0-AJAX example
Getting ready
How to do it...
How it works...
There's more...
See also
Using the f:ajax tag
Getting ready
How to do it...
How it works...
See also
Installing and using Dynamic Faces in NetBeans 6.8
Getting ready
How to do it...
See also
Using the inputSuggestAjax component
Getting ready
How to do it...
How it works...
See also
ajax4jsf—more than 100 AJAX components
Getting ready
How to do it...
How it works...
There's more...
Other ajax4jsf component
See also
Writing reusable AJAX components in JSF 2.0
How to do it...
How it works...
See also
PrimeFaces, CommandLink, and CommandButton
Getting ready
How to do it...
How it works...
There's more...
See also
7. Internationalization and Localization
Introduction
Loading message resource bundles in JSF
Getting ready
How to do it...
How it works...
See also
Using locales and message resource bundles
Getting ready
How to do it...
How it works...
See also
Message resource bundles without f:loadBundle
Getting ready
How to do it...
How it works...
There's more...
See also
Working with parameterized messages
Getting ready
How to do it...
How it works...
See also
Accessing message resource keys from a class
Getting ready
How to do it...
How it works...
See also
Providing a theme to a Visual Web JSF Project
Getting ready
How to do it...
Displaying Arabic, Chinese, Russian, and so on
How to do it...
See also
Selecting a time zone in JSF 2.0
How to do it...
8. JSF, Images, CSS, and JS
Introduction
Injecting CSS in JSF
Getting ready
How to do it...
How it works...
See also
JSF, CSS, and tables
Getting ready
How to do it...
How it works...
There's more...
See also
JSF and dynamic CSS
Getting ready
How to do it...
How it works...
See also
Integrating JavaScript and JSF
Getting ready
How to do it...
How it works...
There's more...
See also
Getting a JSF inputText value from JavaScript
Getting ready
How to do it...
How it works...
See also
Working with JSF hidden fields from JavaScript
Getting ready
How to do it...
How it works...
There's more...
See also
Passing parameters from JS to JSF (client to server)
Getting ready
How to do it...
How it works...
See also
Passing parameters from JSF to JS (server to client)
Getting ready
How to do it...
How it works...
There's more...
See also
Opening a pop-up window using JSF and JS
Getting ready
How to do it...
How it works...
See also
Passing parameters with HTTP GET within the URL
Getting ready
How to do it...
How it works...
See also
Communication between parent pop-up windows
Getting ready
How to do it...
How it works...
See also
Populating a JS load function with JSF values
Getting ready
How to do it...
How it works...
See also
Dynamic images with PrimeFaces
Getting ready
How to do it...
How it works...
See also
Cropping images with PrimeFaces
Getting ready
How to do it...
How it works...
There's more...
See also
Working with rss4jsf project
Getting ready
How to do it...
How it works...
See also
Using resource handlers
Getting ready
How to do it...
How it works...
There's more...
See also
9. JSF—Managing and Testing
Introduction
Managing JSF with Faces Console
Getting ready
How to do it...
Testing JSF applications with JSFUnit
Getting ready
How to do it...
How it works...
There's more...
See also
JSFUnit and Ant
Getting ready
How to do it...
How it works...
See also
JSFUnit API
How to do it...
A JSF and JMeter issue
Getting ready
How to do it...
How it works...
Working with JSF Chart Creator
Getting ready
How to do it...
See also
10. Facelets
Introduction
Installing Facelets under JSF 1.2 (or JSF 1.1)
Getting ready
How to do it...
There's more...
Facelets aliasing components
Getting ready
How to do it...
How it works...
See also
Facelets templating
Getting ready
How to do it...
How it works...
See also
Creating composition components in JSF 2.0
Getting ready
How to do it...
How it works...
See also
Passing sub-elements to composition components
Getting ready
How to do it...
How it works...
See also
Passing actions to composition components
Getting ready
How to do it...
How it works...
See also
11. JSF 2.0 Features
Introduction
JSF 2.0 annotations
How to do it...
Annotations for managed beans
@ResourceDependency annotation
The @ListenerFor annotation
How it works...
Annotations for managed beans
@ResourceDependency annotation
The @ListenerFor annotation
The JSF 2.0 exception handling mechanism
How to do it...
How it works...
See also
Bookmarking JSF pages with PrettyFaces
Getting ready
How to do it...
How it works...
There's more...
See also
JSF declarative event handling
Getting ready
How to do it...
See also
URLs based on specified navigation outcome
Getting ready
How to do it...
How it works...
See also
JSF view parameters
Getting ready
How to do it...
How it works...
See also
JSF 2 and navigation cases
How to do it...
How it works...
12. Mixing JSF with Other Technologies
Introduction
Configuring Seam with JSF
Getting ready
How to do it...
There's more...
Configuring Seam Resource Servlet
Configuring Seam servlet filters
Multipart form submissions
Setting the character encoding
Conversation propagation with redirects
Exception handling
See also
An overview of Seam JSF controls
Getting ready
How to do it...
See also
Mixing JSF and JSTL
Getting ready
How to do it...
How it works...
See also
Integrating JSF and Hibernate
Getting ready
How to do it...
How it works...
Integrating JSF and Spring
Getting ready
How to do it...
How it works...
There's more...
Mixing JSF and EJB (JPA)
Getting ready
How to do it...
How it works...
There's more...
A. Configuring JSF-related Technologies
Apache MyFaces Trinidad (supports JSF 2.0)
RichFaces (supports JSF 2.0)
Apache MyFaces Tomahawk (supports JSF 1.2)
Apache MyFaces Tomahawk Sandbox (supports JSF 1.2)
Apache MyFaces Commons Validators (supports JSF 2.0)
Prime Faces (supports JSF 2.0)
Mojarra Scales (supports JSF 1.2)
j4j (supports JSF 2.0)
rss4jsf (supports JSF 2.0)
Index

JSF 2.0 Cookbook

Anghel Leonard

JSF 2.0 Cookbook

Copyright © 2010 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: June 2010

Production Reference: 1310610

Published by Packt Publishing Ltd.

32 Lincoln Road

Olton

Birmingham, B27 6PA, UK.

ISBN 978-1-847199-52-2

www.packtpub.com

Cover Image by Prasad Hamine (<[email protected]>)

Credits

Author

Anghel Leonard

Reviewer

Edem Morny

Acquisition Editor

Sarah Cullington

Development Editor

Rakesh Shejwal

Technical Editor

Arani Roy

Indexer

Hemangini Bari

Editorial Team Leader

Mithun Sehgal

Project Team Leader

Lata Basantani

Project Coordinator

Poorvi Nair

Proofreader

Chris Smith

Production Coordinator

Shantanu Zagade

Cover Work

Shantanu Zagade

About the Author

Anghel Leonard is a senior Java developer with more than 12 years of experience in Java SE, Java EE, and the related frameworks. He has written and published more than 20 articles and 100 tips and tricks about Java technology. Also, he has written two books about XML and Java (one for beginners and one for advanced users) and another book for Packt Publishing, named JBoss Tools 3 Developer Guide. In this time, he has developed web applications using the latest technologies out in the market. In the past two years, he has focused on developing RIA projects for GIS fields. He is interested in bringing as much desktop to the Web as possible; as a result GIS applications present a real challenge to him.

I would like to thank my family, especially, my wife!

About the Reviewer

Edem Morny has been involved in enterprise Java technologies since he got introduced to Java in 2005, using tools and technologies encompassing both the standard JavaEE stack and non-standard ones such as JBoss Seam, Hibernate, and Spring. His experience with JSF includes working with plain JSF, RichFaces, JBoss Seam, and Spring Web Flow's SpringFaces.

He has been an active promoter of Java EE, speaking at workshops and seminars of a national scale in Ghana.

He is a Senior Developer at the Application Development Center in Accra, Ghana, for an international biometric security solutions company, which is leading the development of Biocryptic Identity Management Systems for the global market.

Edem was a technical reviewer for JBoss Tools 3 Developer Guide and JBoss AS 5 Development both published by Packt Publishing. You'll find him blogging at http://edemmorny.wordpress.com.

Preface

This book will cover all the important aspects involved in developing JSF applications. It provides clear instructions for getting the most out of JSF and offers many exercises to build impressive desktop-style interfaces for your web applications. You will learn to develop JSF applications starting with simple recipes and gradually moving on to complex recipes.

We start off with the simple concepts of converters, validators, and file management. We then work our way through various resources such as CSS, JavaScript, and images to improve your web applications. You will learn to build simple and complex custom components to suit your needs. Next, you get to exploit AJAX as well as implement internationalization and localization for your JSF applications. We then look into ensuring security for your applications and performing testing of your applications. You also get to learn all about Facelets and explore the newest JSF 2.0 features. Finally, you get to learn a few integrations such as JSTL with JSF, Spring with JSF, and Hibernate with JSF. All these concepts are presented in the form of easy-to-follow recipes.

Each chapter discusses separate types of recipes and they are presented with an increasing level of complexity from simple to advanced. All of these recipes can be used with JSF 1.2 as well as JSF 2.0.

What this book covers

Chapter 1, Using Standard and Custom Converters in JSF covers the standard and custom converters in JSF. We start with implicit and explicit conversion examples, then move on to creating and using custom converters, and we end up with client-side converters using MyFaces Trinidad.

Chapter 2, Using Standard and Custom Validators in JSF continues with standard and custom validators. We see how to use a standard validator, how to create and use custom validators, and how to use RichFaces and Apache MyFaces validators. We also present the new JSF 2.0 validators, such as f:validateRegex and f:validateRequired.

Chapter 3, File Management discusses file management issues. You will see different methods for downloading and uploading files, learn how to use JSF Core, RichFaces, PrimeFaces, and Apache Tomahawk. In addition, you will see how to export data to PDF and Excel, and how to extract data from an uploaded CSV file.

Chapter 4, Security covers some security issues. You will see how to use the JSF Security project without JAAS Roles, use secured managed beans with JSF Security, and use Acegi/Spring security in JSF applications.

Chapter 5, Custom Components discusses custom components in JSF. You will see how to build different kinds of custom components in JSF 2.0, Archetypes for Maven, JSF and Dojo and more.

Chapter 6, AJAX in JSF starts with the f:ajax tag, continues with Dynamic Faces, RichFaces, ajax4jsf, and ends up with PrimeFaces and learning to write reusable AJAX components.

Chapter 7, Internationalization and Localization covers internationalization and localization. We will see how to load message resource bundles on JSF pages and how to use locales and message resource bundles. We then move on to parameterized messages, learning how to display Arabic, Chinese, Russian, and so on and how to select time zones in JSF 2.0.

Chapter 8, JSF, Images, CSS, and JS discusses JSF with images, CSS, JS, and RSS. We will integrate JS with JSF, pass values between JS and JSF, crop images, work with dynamic images, work with pop-up windows, RSS support, and so on.

Chapter 9, JSF—Managing and Testing starts with Faces Console, and moves on to JSFUnit and JMeter.

Chapter 10, Facelets covers Facelets recipes. You will see how to work with aliasing components, templates, composition components, passing actions, and sub-elements to composition components.

Chapter 11, JSF 2.0 Features presents some of the most relevant JSF 2.0 features, such as annotations, exception handling mechanism, declarative event handling, URLs based on specified navigation outcome, JSF view parameters, JSF 2.0, and navigation cases.

Chapter 12, Mixing JSF with Other Technologies discusses mixing JSF with other important technologies, such as Spring, Seam, JSTL, Hibernate, and EJB (JPA).

Appendix, Configuring JSF-related Technologies talks about the issues when a JSF-related technology gets into the equation. You need to add some specific configuration, you have to create a "bridge" between JSF and the technology used. This appendix contains the configurations for a few technologies.

What you need for this book

For performing the recipes from this book you will need the following technologies:

JSF 2.0 (or 1.2)NetBeans 6.8GlassFish v3

Also, depending on the recipe, you may also need one of the following technologies:

Acegi SpringApache MavenApache MyFaces CommonsApache TomahawkApache Tomahawk SandboxApache TrinidadDojoDynamic Facesj4jJSF ID GeneratorJSF SecurityJSFUnitMojarra ScalesPretty FacesPrimeFacesRichFacesrss4jsf

Who this book is for

This book is for two types of audience:

Newcomers who know the basics of JSF but are yet to develop real JSF applicationsJSF developers who have previous experience but are lacking best practices and a standard way of implementing functionality

Reader feedback

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 send an e-mail to <[email protected]>, and mention the book title via 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 e-mail <[email protected]>.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book on, 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.

Note

Downloading the example code for the book

Visit https://www.packtpub.com//sites/default/files/downloads/9522_Code.zip to directly download the example code.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the 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 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 will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. 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. Using Standard and Custom Converters in JSF

In this chapter, we will cover:

Working with implicit and explicit conversionsStandard converters for numbersStandard converters for date and timeConverters and NULL valuesCreating and using a custom converterUsing converters for h:selectOneMenuBinding converters to backing bean propertiesRichFaces and standard convertersRichFaces and custom convertersInstance variables in convertersClient-side converters with MyFaces Trinidad

Introduction

Data conversion is the process of converting/transforming one data type into another. Before going further and analyzing some aspects of JSF converters, let's see what they actually are and what they are good for.

For this, let's take an example of a web application in which the user has to fill up a simple form with some information, such as name, age, and date of birth. The server component of our application will receive this information as strings, even if we know that they are a string (the name), an integer (the age), and a date (the date of birth). This is the phase when JSF converters enter into the scene and convert the user input according to application requirements. If the submitted information is not successfully converted then the form is redisplayed (this time an attention message is also displayed) and the user can refill the form. The case repeats until the submitted information is successfully converted to the correct type.

In addition, you should know that JSF provides a set of standard converters (used for the most common conversions) and the possibility to define your own converters, known as custom converters (this kind of converters are very useful when the standard converters can't accomplish the desired conversions). Speaking of standard converters, the following are the most used converters:

Converter IDs

Converter class

javax.faces.Byte

javax.faces.convert.ByteConverter

javax.faces.Float

javax.faces.convert.FloatConverter

javax.faces.BigInteger

javax.faces.convert.BigIntegerConverter

javax.faces.BigDecimal

javax.faces.convert.BigDecimalConverter

javax.faces.Character

javax.faces.convert.CharacterConverter

javax.faces.DateTime

javax.faces.convert.DateTimeConverter

javax.faces.Boolean

javax.faces.convert.BooleanConverter

javax.faces.Double

javax.faces.convert.DoubleConverter

javax.faces.Long

javax.faces.convert.LongConverter

javax.faces.Short

javax.faces.convert.ShortConverter

javax.faces.Integer

javax.faces.convert.IntegerConverter

Some JSF tags that support converters are as follows:

<h:outputText><h:outputLink><h:selectManyListbox><h:selectMaynyMenu><h:inputTextarea><h:inputHidden><h:outputLabel><h:inputText><h:inputSecret><h:selectBooleanCheckbox><h:selectOneRadio><h:selectOneListbox><h:outputFormat><h:selectOneMenu>

Speaking about a converter lifecycle, you should focus on two main phases named: ApplyRequestValuesPhase and RenderResponsePhase. For example, if we assume a form that is submitted with a set of values, a converter for those values, a corresponding backing bean, and a render page, then the application lifecycle will be like this (notice when and where the converter is involved!):

RestoreViewPhase: The backing bean is created and the components are stored into the UIViewRoot.ApplyRequestValuesPhase: The submitted values are decoded and set in the corresponding components in UIViewRoot.ProcessValidationsPhase: The converter getAsObject method receives the submitted values (eventually a potential validator is also called).UpdateModelValuesPhase: The converted (validated) values are set in the backing bean.InvokeApplicationPhase: The phase responsible for form processing.RenderResponsePhase: The values that should be displayed are extracted from a backing bean. The getAsString method of the converter receives these values before rendering. The conversion results are redirected to the result page.

Using the proper converter is the developer's choice. The developer is also responsible for customizing the error messages displayed when the conversion fails. When the standard converters don't satisfy the application needs, the developer can write a custom converter as you will see in our recipes.

Notice that our recipes make use of JSF 2.0 features, such as annotation, new navigation style, and no faces-config.xml file. Especially you must notice the new @FacesConverter annotation for indicating to a normal class that it is a JSF 2.0 converter.

Let's start with a simple recipe about working with implicit and explicit conversions.

Working with implicit and explicit conversions

By implicit conversions, we understand all the conversions that JSF will accomplish automatically, without the presence of an explicit converter (in other words, if you don't specify a converter, JSF will pick one for you). Actually, JSF uses implicit conversion when you map a component's value to a managed bean property of a Java primitive type or of BigInteger and BigDecimal objects.

In this recipe, we will see an example of an implicit and an explicit conversion. Anyway, don't forget that explicit conversion provides greater control over the conversion.

Getting ready

We developed this recipe with NetBeans 6.8, JSF 2.0, and GlassFish v3. The JSF 2.0 classes were obtained from the NetBeans JSF 2.0 bundled library.

How to do it...

Our recipe is based on an imaginary situation where the user should insert their age into a simple JSF form consisting of a text field and a submit button. The submitted age will be implicitly converted and displayed on another simple JSF page. The following is the JSF form (the highlighted code maps the text field's value to the userAge managed bean property of a Java integer type):

<h:form id="AgeForm"> <h:inputText id="userAgeID" required="true" value="#{userBean.userAge}"> </h:inputText> <h:message showSummary="true" showDetail="false" for="userAgeID" style="color: red; text-decoration:overline"/> <br /> <h:commandButton id="submit" action="response?faces- redirect=true" value="Submit Age"/> </h:form>

Note

The preceding code snippet makes uses of the new JSF 2 implicit navigation style. The {page_name}?faces-redirect=true request parameter indicates to JSF to navigate to the {page_name}. There is more about JSF 2 navigation in Chapter 11, JSF 2.0 Features.

The userAge is mapped into a managed bean as shown next:

package users; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; @ManagedBean @SessionScoped public class UserBean { private int userAge; public int getUserAge(){ return this.userAge; } public void setUserAge(int userAge){ this.userAge=userAge; } }

As the userAge is a Java integer, JSF will automatically convert the inserted age to this type (notice that we did not indicate any conversion in the previous code). This is called an implicit conversion. In the case that the inserted age is not an integer, this will be reflected by an error message exposed by the h:message component.

Now, speaking of explicit conversion we can enforce the previous situation by using the UIComponentconverter attribute or f:converter tag nested within a UIComponent. The modifications are reflected in the next two lines:

<!-- explicit conversion using the UIComponent converter attribute --> <h:inputText id="userAgeID" required="true" value="#{userBean.userAge}" converter="javax.faces.Integer"> </h:inputText> <!-- converter tag nested within a UIComponent --> <h:inputText id="userAgeID" required="true" value="#{userBean.userAge}"> <f:converter converterId="javax.faces.Integer"/> </h:inputText>

How it works...

There is no trick here! In the case of implicit conversion, JSF tries to identify which is the appropriate converter to be applied. Obviously, for explicit conversion, JSF tries to apply the indicated converter. When conversion fails, the form is redisplayed and an exception message is fired. Otherwise, the application follows its normal flow.

There's more...

You can mix explicit and implicit conversion over the same managed bean property, but, in this case, you should keep in mind the Java cast rules. For example, if you try to explicitly force an integer to a Byte type you will get an error, as java.lang.Integer type can't be cast to java.lang.Byte type, while a java.lang.Integer can be cast to java.lang.Double.

See also

The code bundled with this book contains a complete example of this recipe. The project can be opened with NetBeans 6.8 and is named: Working_with_implicit_and_explicit_conversion.