ConverterとValidator

Converter

標準コンバータ

BigDecimalConverter

BigIntegerConverter

BooleanConverter

ByteConverter

CharacterConverter

DateTimeConverter

DoubleConverter

EnumConverter

FloatConverter

IntegerConverter

LongConverter

NumberConverter

ShortConverter

<h:inputText id="price" value="#{bookController.book.price}">

<f:convertNumber currencySymbol="$" type="currency" />

</h:inputText>

<h:inputText id="title" value="#{bookController.book.publishedDate}">

<f:convertDateTime pattern="yyyy/MM/dd" />

</h:inputText>

カスタムコンバータ

@FacesConverter(value="myConverter")

public class MyConverter implements Converter {

@Override

public Object getAsObject(

FacesContext ctx, UIComponent component, String value) {

return value;

}


@Override

public String getAsString(

FacesContext ctx, UIComponent component, Object value) {

String target = value.toString();

...

}

}

<h:outputText value="#{book.price}">

<f:converter converterId="myConverter" />

</h:outputText>

或いは

<h:outputText value="#{book.price}" converter="myConverter" />

★Global converter

faces-config.xml

<converter>

<converter-for-class>java.lang.String</converter-for-class>

<converter-class>

xxx.web.faces.converter.MyConverter

</converter-class>

</converter>

Validator

標準バリデータ

DoubleRangeValidator

LengthValidator

LongRangeValidator

MethodExpressionValidator

RequiredValidator

RegexValidator

<h:inputText id="title" value="#{bookController.book.title}" required="true">

<f:validateLength minimum="3" maximum="10" />

</h:inputText>

<h:inputText id="price" value="#{bookController.book.price}">

<f:validateLongLength minimum="1" maximum="100" />

</h:inputText>

<h:inputText id="name" value="#{someBean.name}"

required="true"

requiredMessage="Name is required!"

validator="#{someBean.valid}"

label="message" />

カスタムバリデータ(クラス・レベル)

import javax.faces.validator.Validator;

@FacesValidator(value="myValidator")

public class MyValidator implements Validator {

@Override

public void validate(

FacesContext ctx, UIComponent component, Object value)

throws ValidatorException {

String target = value.toString();

...

if (...) {

String message = MessageFormat.format("xxx", target);

FacesMessage facesMessage =

new FacesMessage(FacesMessage.SEVERITY_ERROR, message, message);

throw new ValidatorException(facesMessage);

}

}

}

<h:inputText id="xxx" value="#{book.price}">

<f:validator validatorId="myValidator" />

</h:inputText>

<h:message for="xxx" />

或いは

<h:inputText id="xxx" value="#{book.price}" validator="myValidator" />

カスタムバリデータ(メソッド・レベル)

public void validateXxx(FacesContext context, UIComponent component, Object value) {

String id = component.getId(); // id = "test"

String text = value.toString();


if (...) {

throw new ValidatorException(new FacesMessage("xxx"));

}

}

<h:inputText id="xxx" value="#{mybean.someValue}" validator="#{mybean.validateXxx}"/>