请注意,我正在为 Web 应用程序使用 Java 和 Spring。
我有一个对象 (objectBean),它包含一个 EnumInnerObject 类型的 EnumSet (enumSet) 作为属性。我将此对象作为 bean 从我的 Controller 传递到我的 .jsp View 。我使用以下 .jsp 代码来绑定(bind)复选框:
<form:form commandName="objectBean" name="whatever" action="./save.htm" method="post">
<form:checkboxes items="${allOptions}" path="enumSet" />
</form:form>
这是我的 Controller initbinder:
@InitBinder
protected void initBinder(WebDataBinder binder) throws Exception{
binder.registerCustomEditor(EnumSet.class, "enumSet", new CustomCollectionEditor(Collection.class){
protected Object convertElement(Object element){
if(element instanceof String){
EnumInnerObject enumInnerObject= EnumInnerObject.valueOf((String)element);
return enumInnerObject;
}
return null;
}
});
在 Controller 中,我传递了 allOptions(与我的 bean 分开),它包含所有 EnumInnerObject 选项,因此显示所有复选框。 “enumSet”是包含适当值的 EnumSet 属性(如果该值包含在 EnumSet 中,则它会自动检查“allOptions”中的正确框)。所有这些都有效,并且 .jsp 正确显示了正确的复选框。但是,问题是当我提交要保存的页面时。我收到以下错误:
java.lang.IllegalArgumentException: Cannot convert value of type [java.lang.String[]] to required type [java.util.EnumSet] for property 'enumSet': PropertyEditor [com.example.controller.MyController$1] returned inappropriate value]
我觉得我必须修改 InitBinder 才能让表单提交工作。有什么想法吗??
谢谢!
最佳答案
坦率地说,我很难想象这个想法会如何运作:EnumSet
集合旨在存储枚举的值,但目前构造它需要知道元素的数量在那个枚举中(=宇宙的大小)。
CustomCollectionEditor
作为构造函数参数传递了一个集合类,因此它需要创建此集合,并且由于上述原因它将失败。此外,CustomCollectionEditor
仅支持有限数量的目标集合(ArrayList
、TreeSet
、LinkedHashSet
,参见 CustomCollectionEditor#createCollection()
).
为了不使事情过于复杂,我建议您使用通用集合,而不是 EnumSet
。否则你需要编写自己的属性编辑器。实现起来并不困难,例如:
binder.registerCustomEditor(EnumSet.class, "enumSet",
new PropertyEditorSupport() {
@Override
public void setValue(Object value) {
EnumSet<EnumInnerObject> set = EnumSet.noneOf(EnumInnerObject.class);
for (String val: (String[]) value) {
set.add(EnumInnerObject.valueOf(val));
}
super.setValue(set);
}
});
关于java - 绑定(bind) Spring :checkboxes to enumset on submit causes error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7324812/