我正在填充一个<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;
}
}
当菜单中的第一个项目由<f:selectItem>
选择并提交表格,然后value
获得在getAsObject()
方法是Select
这是的标签<f:selectItem>
- 列表中的第一项直观上根本不是预期的。
当。。。的时候itemValue
的属性<f:selectItem>
然后设置为空字符串,它会抛出java.lang.NumberFormatException: For input string: ""
in the getAsObject()
方法,即使异常被精确捕获并注册ConverterException
.
这似乎在某种程度上起作用,当return
的声明getAsString()
更改自
return value instanceof Country?((Country)value).getCountryId().toString():null;
to
return value instanceof Country?((Country)value).getCountryId().toString():"";
null
被替换为空字符串,但当有问题的对象是时返回空字符串null
,反过来又会产生另一个问题,如图所示here https://stackoverflow.com/q/23725629/1391249.
如何让这样的转换器正常工作呢?
Also tried with org.omnifaces.converter.SelectItemsConverter
but it made no difference.