Spring BindingResult或FormError是否清除了有错误的字段?

时间:2014-07-22 20:26:29

标签: java spring spring-mvc

我检查了BindingResultFieldError Javadoc(以及来源),但无法找到这个问题的明确答案。当在Spring MVC Controller方法(在POST上)中执行以下代码时,在重新显示表单时,验证失败的字段将显示为空白。这种行为是有意的吗?我可以在所有情况下依赖它(验证失败的字段是否为空白?)

    //  Does the user's email address already exist?
    if (theUser != null) {
        result.addError(new FieldError("theForm", "emailAddress", null, false, new String[] { "theAccount.emailAddress.alreadyInUse" }, null, null));
        return ".createAccount";
    }

1 个答案:

答案 0 :(得分:0)

再次检查FieldError构造函数,根据JavaDocs,第3个参数被拒绝字段值:

rejectedValue - the rejected field value

覆盖值的代码的确切部分位于AbstractBindingResult class:

public Object getFieldValue(String field) {
    FieldError fieldError = getFieldError(field);
    // Use rejected value in case of error, current bean property value else.
    Object value = (fieldError != null ? fieldError.getRejectedValue() :
            getActualFieldValue(fixedField(field)));
    // Apply formatting, but not on binding failures like type mismatches.
    if (fieldError == null || !fieldError.isBindingFailure()) {
        value = formatFieldValue(field, value);
    }
    return value;
}

因此,当您为FieldError类提供null rejectedValue时,表单字段将被清除。或者我,我总是使用rejectValue代替addError

result.rejectValue( "field", "errorCode" );