SpringMVC复选框:自定义类型的自定义绑定/ PropertyEditorSupport

时间:2017-01-13 20:01:22

标签: spring spring-mvc checkbox

这很简单,但我找不到一个好的例子:

我有一个自定义数据类型,我想绑定到SpringMVC复选框,它看起来像这样:是/否:

public enum YesNoDataType {
   YES("Yes"), 
   NO("No");
}

SpringMVC复选框自动映射到布尔值,现在我需要映射Selected-> YES,Empty-> NO。

我知道我必须实现这4个PropertyEditorSupport方法中的一个,但是哪些方法,以及如何实现?

<form:checkbox path="testYesNo"></form:checkbox>

模型

private YesNoDataType testYesNo; 

控制器

binder.registerCustomEditor(YesNoDataType.class, new PropertyEditorSupport() {

          // Which ones to override?

            @Override
            public void setValue(Object value) {
                // TODO Auto-generated method stub
                super.setValue(value);
            }

            @Override
            public Object getValue() {
                // TODO Auto-generated method stub
                return super.getValue();
            }

            @Override
            public String getAsText() {
                // TODO Auto-generated method stub
                return super.getAsText();
            }

            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                // TODO Auto-generated method stub
                super.setAsText(text);
            }

});

1 个答案:

答案 0 :(得分:0)

我尝试定义和注册一些转换器(YesNoDataType / Boolean),但我在SpringMVC的CheckboxTag.java中看到它们都没用。没有转换器或绑定调整将起作用,因为标签仅明确检查布尔和字符串

protected void writeTagDetails(TagWriter tagWriter) throws JspException {
    tagWriter.writeAttribute("type", getInputType());

    Object boundValue = getBoundValue();
    Class<?> valueType = getBindStatus().getValueType();

    if (Boolean.class.equals(valueType) || boolean.class.equals(valueType)) {
        // the concrete type may not be a Boolean - can be String
        if (boundValue instanceof String) {
            boundValue = Boolean.valueOf((String) boundValue);
        }
        Boolean booleanValue = (boundValue != null ? (Boolean) boundValue : Boolean.FALSE);
        renderFromBoolean(booleanValue, tagWriter);
    }

    else {
        Object value = getValue();
        if (value == null) {
            throw new IllegalArgumentException("Attribute 'value' is required when binding to non-boolean values");
        }
        Object resolvedValue = (value instanceof String ? evaluate("value", value) : value);
        renderFromValue(resolvedValue, tagWriter);
    }
}

String绑定与我无关。在getValue()字符串绑定(第2节)中,如果其value=""属性与模型中的字符串匹配,则会选中一个复选框。我需要的是一个True / False布尔绑定,但我的转换器需要插入到条款#1中以从自定义类型获取布尔值。只是非常沮丧,一旦你试图超越常见的狭隘参数,Spring就是如此限制。问题仍然很突出。