最近一直在使用icefaces,发现select*系统组件在binding一个非字符型的bean属性总是会报“验证错误”的error message。其原因在于JSF的默认实现只针对字符型进行binding。如果想要对任意类型进行binding,就需要自己编写converter了。以Long型为例:
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import org.apache.commons.lang.math.NumberUtils;
public class LongConvert implements Converter {
public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2)
throws ConverterException {
return NumberUtils.toLong(arg2, 0);
}
public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2)
throws ConverterException {
return arg2.toString();
}
}
javax.faces.convert.Converter接口有两个方法需要实现,其中getAsObject()是JSF组件在回写前端数据到后台bean的时候调用,其中第三个参数是一个string类型,我们可以根据这个String类型的值返回一个符合我们业务逻辑的Object,这里我返回了一个Long;getAsString()是JSF组件根据后台binding的bean获取前端可选值的时候调用,第二个参数是一个Object对象,可以按业务逻辑转换为我们需要的String值提供给前端。
这个自定义的Converter需要在faces-config.xml中配置才能生效
<converter> <converter-id>longConvert</converter-id> <converter-class>LongConvert</converter-class> </converter>
那么在我们的JSF页面中配置需要的select*组件使用这个converter即可
<ice:selectOneMenu value="#{bean.id}" converter="longConvert">
<f:selectItems value="#{xxxx}"/>
</ice:selectOneMenu>
通过自定义的converter,还可以将复杂的业务对象和前端进行binding