如何解决如何为Spring的表单选择列表设置自定义PropertyEditorSupport.setAsTextString?
| 我有一个弹簧形式。该表单包含一个绑定到枚举类型的选择列表。我还向未在枚举中表示的选择列表中添加了一个“选择”选项。 我在网上看到一些线程,人们建议使用propertyeditor以避免修改枚举,并避免spring在\“ choose \”选项和枚举之间引发转换错误(用户可以将选项保留为select-it \在某些情况下是可选的) 我创建了一个propertyeditor,并在两种情况下进行了尝试。如果我尝试将其与选择列表一起使用(如下所述),则该表单将不会加载,并且spring会引发错误:没有枚举const类com.mytest.domain.Box.Choose。如果我不包括我的自定义编辑器,则表单可以很好地加载,唯一的问题是提交表单时,错误对象将包含错误,抱怨从java.lang.String到BoxType转换失败。如果我将表单切换为form:input而不是form:select,则该表单将加载,并且仅当我输入的值不是Enum值之一后提交时,才会引发错误。如果输入有效值,可以看到未调用我的BoxEditor.setAsText()
。加载表单时会调用BoxEditor.getAsText()
(猴子的大脑是输入字段中的值)。我不知道为什么调用get方法而不是调用set。任何帮助将不胜感激。
我定义了一个枚举:
public enum BoxType {
SMALL,MEDIUM,LARGE
}
还有一个Domain对象:
public class BoxRequest {
private BoxType Box;
public BoxType getBox() {
return Box;
}
public void setBox(BoxType b) {
this.Box = b;
}
}
我已经使用jstl和spring's form tagilb创建了一个jsp
<%@ taglib uri=\"http://java.sun.com/jsp/jstl/core\" prefix=\"c\" %>
<%@ taglib uri=\"http://www.springframework.org/tags\" prefix=\"s\" %>
<%@ taglib uri=\"http://www.springframework.org/tags/form\" prefix=\"form\" %>
<html>
<head>
<title>Box Form</title>
</head>
<body>
<form:form id=\"Boxrequest\" method=\"post\" modelattribute=\"Boxrequest\">
<form:label path=\"Box\">Choose a Box size*</form:label>
<form:input path=\"Box\"/>
<!-- really want the form to use this once I get it working
<form:select multiple=\"single\" path=\"Box\">
<form:option value=\"Choose\"/>
<form:options/>
</form:select>
-->
</form:form>
</body>
</html>
我的propertyeditor
public class BoxTypeEditor extends propertyeditorSupport {
@Override
public void setAsText(String s) {
System.out.println(\"This output is never printed :( \");
if(StringUtils.hasText(s))
setValue(Enum.valueOf(BoxType.class,s));
else
setValue(null);
}
@Override
public String getAsText() {
System.out.println(\"this output shows when the form loads\");
if(getValue() == null) {
return \"monkeybrains\";
}
BoxType b = (BoxType) getValue();
return b.toString();
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。