Java Reference
In-Depth Information
to generate the appropriate output. When the JavaServer Faces implementation calls this
method, it passes in the current
FacesContext
, the
UIComponent
whose value needs
to be converted, and the bean value to be converted. Because this converter does a
String
-to-
String
conversion, this method can cast the bean value to a
String
.
If the value cannot be converted to a
String
, the method throws an exception, passing
tering Application Messages
”
on page
155
explains how to register custom error messages
with the application.
If the value can be converted to a
String
, the method reads the
String
to a character
array and loops through the array, adding a space after every four characters.
You can also create a custom converter with a
@FacesConverter
annotation that spe-
cifies the
forClass
attribute, as shown in the following example from the Duke's Tutor-
ing case study:
@FacesConverter(forClass=Guardian.class)
public class GuardianConverter implements Converter { ...
The
forClass
attribute registers the converter as the default converter for the
Guard-
ian
class. Therefore, whenever that class is specified by a
value
attribute of an input
component, the converter is invoked automatically.
A converter class can be a separate Java POJO class, as in the Duke's Bookstore and
Duke's Tutoring case studies. If it needs to access objects defined in a managed bean class,
however, it can be a subclass of a JavaServer Faces managed bean, as in the Duke's Forest
case study, where the converters use an enterprise bean that is injected into the managed
bean class.
Using a Custom Converter
To apply the data conversion performed by a custom converter to a particular component's
value, you must do one of the following:
• Reference the converter from the component tag's
converter
attribute.
• Nest an
f:converter
tag inside the component's tag and reference the custom
converter from one of the
f:converter
tag's attributes.
If you are using the component tag's
converter
attribute, this attribute must reference
the
Converter
implementation's identifier or the fully-qualified class name of the con-