【发布时间】:2013-06-07 19:09:33
【问题描述】:
我正在从数据库中填充<p:selectOneMenu/>,如下所示。
<p:selectOneMenu id="cmbCountry"
value="#{bean.country}"
required="true"
converter="#{countryConverter}">
<f:selectItem itemLabel="Select" itemValue="#{null}"/>
<f:selectItems var="country"
value="#{bean.countries}"
itemLabel="#{country.countryName}"
itemValue="#{country}"/>
<p:ajax update="anotherMenu" listener=/>
</p:selectOneMenu>
<p:message for="cmbCountry"/>
加载此页面时默认选择的选项是,
<f:selectItem itemLabel="Select" itemValue="#{null}"/>
转换器:
@ManagedBean
@ApplicationScoped
public final class CountryConverter implements Converter {
@EJB
private final Service service = null;
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
try {
//Returns the item label of <f:selectItem>
System.out.println("value = " + value);
if (!StringUtils.isNotBlank(value)) {
return null;
} // Makes no difference, if removed.
long parsedValue = Long.parseLong(value);
if (parsedValue <= 0) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "", "Message"));
}
Country entity = service.findCountryById(parsedValue);
if (entity == null) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_WARN, "", "Message"));
}
return entity;
} catch (NumberFormatException e) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "", "Message"), e);
}
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
return value instanceof Country ? ((Country) value).getCountryId().toString() : null;
}
}
When the first item from the menu represented by <f:selectItem> is selected and the form is submitted then, the value obtained in the getAsObject() method is Select which is the label of <f:selectItem> - the first列表中的项目,这在直觉上是完全不期望的。
当<f:selectItem> 的itemValue 属性设置为空字符串时,它会在getAsObject() 方法中抛出java.lang.NumberFormatException: For input string: "",即使该异常已被精确捕获并为ConverterException 注册。
当getAsString() 的return 语句从
return value instanceof Country?((Country)value).getCountryId().toString():null;
到
return value instanceof Country?((Country)value).getCountryId().toString():"";
null 被空字符串替换,但当相关对象为 null 时返回空字符串,进而引发另一个问题,如 here 所示。
如何让这类转换器正常工作?
也尝试了org.omnifaces.converter.SelectItemsConverter,但没有任何区别。
【问题讨论】:
-
你考虑过这个
<f:selectItem itemLabel="Select" noSelectionOption="true" />吗? -
我在这篇文章之前尝试使用
noSelectionOption="true"- 一年前,但它似乎也没有任何区别。
标签: jsf primefaces converter jsf-2.2 selectonemenu