JSF 2: noSelectionOption problem for selectOneMenu with converter

I am currently testing using the f: selectItems tag , which uses existing POJO classes.

This works fine:

facelet:

<h:selectOneMenu value="#{selectionLabBean.oneSelectMenuPojo}" 
    converter="heroConverter">
    <f:selectItems value="#{selectionLabBean.heroList}" 
        var="hero" itemValue="#{hero}" itemLabel="#{hero.name}" />
</h:selectOneMenu>

bean:

private HeroBean oneSelectMenuPojo;
public HeroBean getOneSelectMenuPojo() {
    return oneSelectMenuPojo;
}
public void setOneSelectMenuPojo(HeroBean oneSelectMenuPojo) {
    this.oneSelectMenuPojo = oneSelectMenuPojo;
}

And then, I want to add the "Choose one .." selection, I did this:

facelet:

<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>

and this exception will happen:

java.lang.ClassCastException: java.lang.String could not be added to user .ui.HeroBean

I think I understand the problem. Im uses a converter to display POJO for selection and vice versa, and "Select one" for string. But I also want to put the line "Choose one ..". What can I do to solve this problem?

Here is my converter class:

@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();
    }
}
+3
source share
2 answers

:

<f:selectItem itemLabel="Choose one .." 
        noSelectionOption="true"/>

<f:selectItem itemValue="#{null}" itemLabel="Choose one .." 
        noSelectionOption="true"/>
+10

, @FacesConverter forClass value, noSelectionOption (getAsString noSelectionOption)! , .

, :

@FacesConverter(forClass= HeroBean.class)

@FacesConverter("heroConverter")

( convert = "heroConverter" selectOneMenu)

, , Mojarra 2.0.2 GlassFish 3.0.1. , , , .

+1

Source: https://habr.com/ru/post/1782557/


All Articles