我目前正在测试使用f:selectItems标签,它使用现有的POJO类.
小面孔:
<h:selectOneMenu value="#{selectionLabBean.oneSelectMenuPojo}"
converter="heroConverter">
<f:selectItems value="#{selectionLabBean.heroList}"
var="hero" itemValue="#{hero}" itemLabel="#{hero.name}" />
</h:selectOneMenu>
Run Code Online (Sandbox Code Playgroud)
托管bean:
private HeroBean oneSelectMenuPojo;
public HeroBean getOneSelectMenuPojo() {
return oneSelectMenuPojo;
}
public void setOneSelectMenuPojo(HeroBean oneSelectMenuPojo) {
this.oneSelectMenuPojo = oneSelectMenuPojo;
}
Run Code Online (Sandbox Code Playgroud)
小面孔:
<h:selectOneMenu value="#{selectionLabBean.oneSelectMenuPojo}"
converter="heroConverter">
<f:selectItem itemValue="NONE" itemLabel="Choose one .."
noSelectionOption="true"/>
<f:selectItems value="#{selectionLabBean.heroList}"
var="hero" itemValue="#{hero}" itemLabel="#{hero.name}" />
</h:selectOneMenu>
Run Code Online (Sandbox Code Playgroud)
这将发生异常:
java.lang.ClassCastException:java.lang.String无法强制转换为user.ui.HeroBean
我想我明白了这个问题.我使用转换器将POJO映射到选择,反之亦然,"选择一个"映射到字符串.但我也想把"选择一个......"的字符串.我该怎么做才能解决这个问题?
这是我的转换器类:
@FacesConverter("heroConverter")
public class HeroBeanConverter implements Converter {
@Override
public Object getAsObject(FacesContext context, UIComponent ui,
String newValue) {
return HeroBean.findHeroBeanByName(newValue);
}
@Override
public String getAsString(FacesContext context, UIComponent component,
Object value) {
return ((HeroBean) value).getName();
}
}
Run Code Online (Sandbox Code Playgroud)
Mic*_*rdt 10
其中一个应该工作:
<f:selectItem itemLabel="Choose one .."
noSelectionOption="true"/>
<f:selectItem itemValue="#{null}" itemLabel="Choose one .."
noSelectionOption="true"/>
Run Code Online (Sandbox Code Playgroud)