如何为Spring的表单选择列表设置自定义PropertyEditorSupport.setAsText(String)?

| 我有一个弹簧形式。该表单包含一个绑定到枚举类型的选择列表。我还向未在枚举中表示的选择列表中添加了一个“选择”选项。 我在网上看到一些线程,人们建议使用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();
    }
}
    
已邀请:

要回复问题请先登录注册