我检查了BindingResult和FieldError 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";
}
答案 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" );