12.07.2015 Views

Beginning Java EE 6 with GlassFish 3, Second Edition

Beginning Java EE 6 with GlassFish 3, Second Edition

Beginning Java EE 6 with GlassFish 3, Second Edition

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 12 ■ PROCESSING AND NAVIGATIONThe convertDateTime tag can convert dates in various formats (date, time, or both). It has severalattributes that control the date conversion and time zones. A pattern attribute allows identification ofthe pattern of the date string that will be converted.Custom ConvertersSometimes converting numbers, dates, enums, and so on is insufficient, and you may require customconversion. It is easy to develop your own converters and use them in pages <strong>with</strong> JSF. You simply have towrite a class that implements the javax.faces.convert.Converter interface and register it <strong>with</strong>metadata. This interface has two methods:Object getAsObject(FacesContext ctx, UIComponent component, String value)String getAsString(FacesContext ctx, UIComponent component, Object value)The getAsObject() method converts the string value of a UI component into the correspondingsupported type and returns the new instance. This method throws a ConverterException if theconversion fails. Conversely, the getAsString() method converts the provided type to a string, to berendered in markup language (such as XHTML).Once the custom converter is developed, it must be registered to allow it to be used in the webapplication. One method is by declaring the converter in the faces-config.xml file; the other is to use the@FacesConverter annotation.Listing 12-12 shows how to write a custom converter that converts a price from dollars to euros. Itstarts by associating this converter <strong>with</strong> the name euroConverter (value = "euroConverter") using the@FacesConverter annotation, and implements the Converter interface. This example only overrides thegetAsString() method, which returns a string representation of a given price in euros.Listing 12-12. A Euro Converter@FacesConverter(value = "euroConverter")public class EuroConverter implements Converter {@Overridepublic Object getAsObject(FacesContext ctx, UIComponent component, String value) {return value;}}@Overridepublic String getAsString(FacesContext ctx, UIComponent component, Object value) {float amountInDollars = Float.parseFloat(value.toString());double ammountInEuros = amountInDollars * 0.8;DecimalFormat df = new DecimalFormat("###,##0.##");return df.format(ammountInEuros);}365

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!