Java 丰富:选择“显示”;值不是有效选项";选择项目并将其转换为对象后
我在Java 丰富:选择“显示”;值不是有效选项";选择项目并将其转换为对象后,java,validation,jsf,richfaces,converter,Java,Validation,Jsf,Richfaces,Converter,我在rich:select中列出了类型为Test(来自我的域)的元素集合,使用以下代码: 测试.xtml <rich:select value="#{testBean.test}" id="cmbTest" converter="#{testConverter}" enableManualInput="false"> <f:selectItems value="#{testBean.all}" var="test" itemLabel="#{test.name}
rich:select
中列出了类型为Test
(来自我的域)的元素集合,使用以下代码:
测试.xtml
<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" />
(您可能注意到,我使用的是Spring)xhtml文件的支持bean定义如下:
TestBean.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();
}
}
@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;
}
}
@Controller(“testBean”)
@范围(“会议”)
公共类TestBean{
私人测试;
私人名单所有;
公共TestBean(){
all=新的ArrayList();
对于(inti=0;i<15;i++){
添加(新测试(1,String.format(“测试%d”,i));
}
}
公共测试getTest(){
回归试验;
}
公共作废保存(){
System.out.println(“保存”);
}
公共列表getAll(){
全部归还;
}
}
选择有效项后按“保存”按钮,出现验证错误:“值不是有效选项”,如下图:
我已经调试了ConvertergetAsObject
调用,它工作正常,按预期返回一个有效的Test
实例(实际上,这个“Test”project是我第一次发现这个问题的工作项目的一个独立案例,在该项目中,转换器成功地使用注入服务从数据库中检索对象)
显然,beansave
方法永远不会被调用,因为视图会因为这个错误而卡在jsf验证fase中
试图将rich:select
替换为h:selectOneMenu
,但相同。我已经浏览了很多jsf转换器教程/docs/refs,但我仍然不知道我会做错什么
我使用的是maven和Richfaces BOM配置,正如所指出的,用4.2.2.Final替换了这个版本(希望更新可以修复它)
我发布了
任何帮助都将不胜感激,我花了这么多时间试图找到解决方案,可能是一些简单/愚蠢的事情,但我只是厌倦了调试/搜索您需要实现
equals()
和hashCode())
在您的测试
类中,以便JSF可以在项目列表中找到您选择并转换的项目。转换后,JSF会将所选项目与列表中的项目进行比较,如果没有找到,则会引发此错误