【问题标题】:rich:select shows "Value is not valid option" after selecting and converting the item to an objectrich:select 在选择项目并将其转换为对象后显示“值无效选项”
【发布时间】:2012-10-09 14:04:12
【问题描述】:

我使用以下代码在rich:select 中列出了Test 类型的元素集合(来自我的域):

test.xml

<rich:select value="#{testBean.test}" id="cmbTest"
    converter="#{testConverter}" enableManualInput="false">
    <f:selectItems value="#{testBean.all}" var="test" itemLabel="#{test.name}" />
</rich:select>
<rich:message for="cmbTest" />
<h:commandButton id="btnSave" action="#{testBean.save}" value="Save" />

我还有一个自定义的 jsf 转换器,可以将选择的字符串值转换为 Test 类型的对象,反之亦然:

TestConverter.java

@Component
@Scope("request")
public class TestConverter implements Converter {
    @Override
    public Object getAsObject(FacesContext facescontext, UIComponent uicomponent, String value) {
        if (value == null) return null;
        return new Test(Integer.parseInt(value), "test" + value);
    }

    @Override
    public String getAsString(FacesContext facescontext, UIComponent uicomponent, Object obj) {
        if (obj == null) return null;
        return ((Test) obj).getId().toString();
    }
}

(您可能注意到,我使用的是 Spring)xhtml 文件的 backing-bean 定义如下:

TestBean.java

@Controller("testBean")
@Scope("session")
public class TestBean {
    private Test test;
    private List<Test> all; 

    public TestBean() {
        all = new ArrayList<Test>();
        for (int i = 0; i < 15; i++) { 
            all.add(new Test(1, String.format("test%d", i)));    
        }
    }

    public Test getTest() {
        return test;
    }

    public void save() {
        System.out.println("Save");
    }

    public List<Test> getAll() {
        return all;
    }
}

当我选择一个有效的项目后按下“保存”按钮,我得到验证错误:“Value is not a valid option”,如下图:

我已经调试了 Converter getAsObject 调用,它工作正常,它按预期返回一个有效的 Test 实例(事实上,这个“测试”项目是我第一次发现这个问题的工作项目的一个孤立案例,并且在该项目中,转换器成功使用注入服务从数据库中检索对象)。

显然 bean save 方法永远不会被调用,因为视图卡在 jsf 验证过程中并出现此错误。

尝试将rich:select 替换为h:selectOneMenu,但结果相同。我浏览了很多 jsf-converter tutorials/docs/refs,但我仍然不知道我做错了什么。

我正在使用 maven 和 Richfaces BOM 配置,正如 here 指出的那样,用 4.2.2.Final 替换了版本(希望更新可以修复它)

我发了test project here

任何帮助将不胜感激,我花了很多时间试图找到解决方案,也许是一些简单/愚蠢的事情,但我只是厌倦了调试/搜索

【问题讨论】:

    标签: java validation jsf richfaces converter


    【解决方案1】:

    您需要在您的Test 类中实现equals()hashCode(),以便JSF 可以在项目列表中找到您选择和转换的项目。转换后,JSF 会将所选项目与列表中的项目进行比较,如果没有找到,则会引发此错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-16
      • 1970-01-01
      • 2021-06-22
      • 1970-01-01
      • 2020-07-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多