Вы находитесь на странице: 1из 10

Validators and Converters

Java Server Faces provides the ability to both convert and validate user provided data to help ensure data integrity. Conversion Data conversion is the process of converting, or transforming, one data type into another. JSF will provide implicit conversion when you map a components value to a managed bean property of a Java primitive type or Object types of BigDecimal and BigInteger. Alternatively JSF provides a set of standard converters that may be explicitly specified using the converter attribute of a UIComponent tag. Lets take a look at both the implicit and explicit conversion techniques. Implicit conversion

Explicit conversion using the UIComponent converter attribute

JSF provides support for several standard conversion types.


BigDecimal BigInteger Boolean Byte

Character DateTime Double Float Integer Long Number Short

JSF also supplies converter tags that may be nested within a UIComponent.

DateTime and Number Converter tags DateTime and Number converter tags supply attributes that may be used for additional data conversion precision. DateTime Converter This is my favorite converter with several options that make, the often painful, job of date conversion so much easier. Lets take a look at the list of attributes and their values.

dateStyle o default Jan 1, 2006 1:20:45 PM o short 1/1/06 1:20:45 PM o medium - Jan 1, 2006 1:20:45 PM o long - January 1, 2006 1:20:45 PM o full - Sunday, January 1, 2006 1:20:45 PM locale o java.util.Locale(String language, String country) o Locale.SPAIN, Locale.CANADA, etc. pattern o Java.text.SimpleDateFormat o yyyy.MM.dd at HH:mm:ss z 2007.01.01 at 12:05:30 PDT o EEE, MMM d yy - Mon, Jan 1, 07

h:mm a 10:05 AM hh o clock a, zzzz - 12 o clock PM, Pacific Daylight Time timeStyle o default Jan 1, 2007 10:05:30 AM o short - 1/1/07 10:05:30 AM o medium - Jan 1, 2006 10:05:30 AM o long - January 1, 2007 10:05:30 AM o full - Monday, January 1, 2006 10:05:30 AM timeZone o java.util.TimeZone type o both Date and time. o date Date only. o time Time only.
o o

Here is a simple output-text example of a convertDateTime tag

Now lets look at an input-text example

User input must be in the MM/dd/yyyy format, otherwise they will receive an error stating such. The JSF implementation will convert the input from a String into a java.util.Date.

Number Converter Number converters are excellent for formatting the display of numeric data. Lets take a look at the standard converters and their attributes.

currencyCode o The ISO 4217 currency code, applied only when formatting currencies. A three-letter codes such as USD for the United States Dollar, GBP for the United Kingdom Pound, and EUR for the Euro. I found that not all codes listed in ISO 4217 were implemented. currencySymbol o Currency symbol, is applied only when formatting currencies. If the currency code is set then currencySymbol will be ignored. This is the literal currency symbol, such as $. groupingUsed o Flag specifying whether formatted output will contain grouping separators. Default value is true. integerOnly o Flag specifying whether only the integer part of the value will be formatted and parsed. Default value is false. maxFractionDigits o Maximum number of digits that will be formatted in the fractional portion of the output. maxIntegerDigits o Maximum number of digits that will be formatted in the integer portion of the output. minFractionDigits o Minimum number of digits that will be formatted in the fractional portion of the output. minIntegerDigits o Minimum number of digits that will be formatted in the integer portion of the output. locale o A java.util.Locale used to define a language and country. If not specified, the Locale returned by FacesContext.getViewRoot().getLocale() will be used. pattern o Custom formatting pattern which determines how the number string should be formatted and parsed. Examples

o o

type
o

###,### 123,456 $###,###.## - $123,456.99 #.### 1.789 Specifies the number type. Valid values are number, currency, and percent. Default value is number.

In this currency example we use the locale attribute to format a currency value. The locale attribute is very helpful when supporting internalization.

Custom converters If the standard converters do not fulfill yours needs then you may want to create your own. There are several steps to creating a custom converter including 1. Create a converter class that implements the javax.faces.convert.Converter interface. 2. Implement the getAsObject() and getAsString() methods within your converter class. 3. Register your converter in faces-config.xml. 4. Use the <f:converter> tag in your page view. This example is a custom converter that formats an SSN by inserting - separators for output display, and stripping the - separators when retrieving the SSN from UIInput component.

Validators Validators can be specified using a components validator attribute or by nesting JSF provided tags. Validation can be performed only on UIInput components or components whose classes extend UIInput. Using the validator attribute of a UIInput component allows you to specify a custom validator or a validate method on a managedBean.

When using the standard Validator implementations, you dont need to write any code to perform validation. You simply nest the standard validator tag of your choice inside a tag that represents a component of type UIInput (or a subclass of UIInput) and provide the necessary constraints. Lets look at the JSF supplied standard validators.

LengthValidator - Checks whether the length of a components value is within a certain range. This validator counts the number of characters. o Minimum The minimum acceptable number of characters. o Maximum The maximum acceptable number of characters. LongRangeValidator - Checks whether the value of a component is within a certain range. The validator will attempt to convert the number to a Java long primitive. If minimum and maximum attributes are used the validator will ensure that the value entered is within the minimum and maximum range. If the minimum and maximum attribute are omitted then the validator ensures that the value is numeric. o Minimum The minimum acceptable numeric value. o Maximum The maximum acceptable numeric value. DoubleRangeValidator - Checks whether the value of a component is within a certain range. The value must be numeric or convertible to a numeric value. The validator will attempt to convert the number into a Java double primitive. If minimum and maximum attributes are used the validator will ensure that the value entered is within the minimum and maximum range. If the minimum and maximum attribute are omitted then the validator only ensures that the value is numeric. o Minimum The minimum acceptable numeric value. o Maximum The maximum acceptable numeric value.

LengthValidator

LongRangeValidator

DoubleRangeValidator

Custom ManagedBean Validator You may place a custom validator method within a managedBean and bind it to the validator attribute of any UIInput component. When adding a validator to a managed bean the validator method must accept (FacesContext context, UIComponent toValidate, Object value) as method parameters.

Custom Validator JSF makes it very easy to create a custom validator class and tag. Your custom validator class must implement the

javax.faces.validator.Validator interface which will require a validate method. Next you will need to register your validator in faces-config.

Requiring a Value If a UIInput component does not have the required attribute set to true and the user does not enter a value, then the validator will not be called. Remember to set required=true, if you want to force validation.

Вам также может понравиться