驗(yàn)證功能在Spring中是很常用的伴逸。你可以使用注解或自己的驗(yàn)證器并將其綁定到請(qǐng)求中蜀踏。本文將重點(diǎn)介紹第一種解決方案撬码。第一部分將介紹注解驗(yàn)證流程儿倒。在第二部分中,將介紹基本實(shí)現(xiàn)的組件呜笑。最后一部分將包含Spring初學(xué)者開(kāi)發(fā)人員常見(jiàn)錯(cuò)誤的解釋:是否有必要直接在驗(yàn)證對(duì)象之后放置BindingResult夫否。
使用@Valid注解在Spring中進(jìn)行驗(yàn)證流程
要了解使用標(biāo)準(zhǔn)Java @Valid或特定Spring @Validated注解的驗(yàn)證過(guò)程,我們首先需要了解Spring如何解析使用了@ModelAttribute注解的對(duì)象叫胁。它們?cè)赾ontroller的方法簽名進(jìn)行注解凰慈。@ModelAttribute注解用于將動(dòng)態(tài)請(qǐng)求參數(shù)轉(zhuǎn)換為Java注解中指定的對(duì)象。例如驼鹅,觀察代碼@ModelAttribute(“article”)Article article ,Spring會(huì)嘗試將所有請(qǐng)求參數(shù)匹配到Article類的字段中∥⑽剑現(xiàn)在,假設(shè)這個(gè)類有兩個(gè)字段:title和content输钩。如果請(qǐng)求包含title和content參數(shù)豺型,它們將被用作Article的title和content的值(后面會(huì)對(duì)@ModelAttribute方面的源碼做進(jìn)一步的分析)。
當(dāng)我們有對(duì)象需要進(jìn)行驗(yàn)證時(shí)买乃,@ModelAttribute注解的處理器(org.springframework.web.method.annotation.ModelAttributeMethodProcessor)會(huì)檢查是否必須應(yīng)用驗(yàn)證注解姻氨。注解驗(yàn)證必須以“Valid”這個(gè)字眼開(kāi)頭。接下來(lái)剪验,對(duì)象通過(guò)org.springframework.validation.DataBinder類中的public void validate(Object … validationHints)進(jìn)行驗(yàn)證肴焊。該方法遍歷所有可用的驗(yàn)證器,并調(diào)用每個(gè)驗(yàn)證器的validate方法功戚。驗(yàn)證器取自帶有validatorID的bean娶眷。這樣,它可以與annotation-driven的xml配置相關(guān)聯(lián):
<mvc:annotation-driven validator="validator" >
如果未指定驗(yàn)證器bean疫铜,則將使用默認(rèn)驗(yàn)證器:org.springframework.validation.beanvalidation.LocalValidatorFactoryBean茂浮。
如何在Spring中處理驗(yàn)證?
我們已經(jīng)了解了驗(yàn)證流程】枪荆現(xiàn)在席揽,我們可以專注于驗(yàn)證過(guò)程本身,即驗(yàn)證器是如何知道一個(gè)字段不正確的谓厘。LocalValidatorFactoryBean繼承自同一個(gè)包下的SpringValidatorAdapter幌羞,但不會(huì)覆蓋其的validate()方法。這些方法用于檢查驗(yàn)證字段是否正確竟稳。更準(zhǔn)確地說(shuō)属桦,SpringValidatorAdapter包含一個(gè)目標(biāo)驗(yàn)證器字段(Validator類型的targetValidator)熊痴。它將在validate()方法中使用來(lái)驗(yàn)證已驗(yàn)證對(duì)象的所有字段。
public class SpringValidatorAdapter implements SmartValidator, javax.validation.Validator {
private static final Set<String> internalAnnotationAttributes = new HashSet<>(3);
static {
internalAnnotationAttributes.add("message");
internalAnnotationAttributes.add("groups");
internalAnnotationAttributes.add("payload");
}
@Nullable
private javax.validation.Validator targetValidator;
/**
* Create a new SpringValidatorAdapter for the given JSR-303 Validator.
* @param targetValidator the JSR-303 Validator to wrap
*/
public SpringValidatorAdapter(javax.validation.Validator targetValidator) {
Assert.notNull(targetValidator, "Target Validator must not be null");
this.targetValidator = targetValidator;
}
SpringValidatorAdapter() {
}
void setTargetValidator(javax.validation.Validator targetValidator) {
this.targetValidator = targetValidator;
}
...
@Override
public void validate(@Nullable Object target, Errors errors) {
if (this.targetValidator != null) {
processConstraintViolations(this.targetValidator.validate(target), errors);
}
}
@Override
public void validate(@Nullable Object target, Errors errors, @Nullable Object... validationHints) {
if (this.targetValidator != null) {
Set<Class<?>> groups = new LinkedHashSet<>();
if (validationHints != null) {
for (Object hint : validationHints) {
if (hint instanceof Class) {
groups.add((Class<?>) hint);
}
}
}
processConstraintViolations(
this.targetValidator.validate(target, groups.toArray(new Class<?>[groups.size()])), errors);
}
}
此驗(yàn)證的結(jié)果是由在SpringValidatorAdapter內(nèi)的protected void processConstraintViolations(Set<ConstraintViolation<Object>> violations, Errors errors)方法處理得到聂宾。它將錯(cuò)誤從JSR-303驗(yàn)證器附加到給定的Spring的錯(cuò)誤對(duì)象(覺(jué)得別扭請(qǐng)看下面方法上的英文注釋)果善。
/**
* Process the given JSR-303 ConstraintViolations, adding corresponding errors to
* the provided Spring {@link Errors} object.
* @param violations the JSR-303 ConstraintViolation results
* @param errors the Spring errors object to register to
*/
protected void processConstraintViolations(Set<ConstraintViolation<Object>> violations, Errors errors) {
for (ConstraintViolation<Object> violation : violations) {
String field = determineField(violation);
FieldError fieldError = errors.getFieldError(field);
if (fieldError == null || !fieldError.isBindingFailure()) {
try {
ConstraintDescriptor<?> cd = violation.getConstraintDescriptor();
String errorCode = determineErrorCode(cd);
Object[] errorArgs = getArgumentsForConstraint(errors.getObjectName(), field, cd);
if (errors instanceof BindingResult) {
// Can do custom FieldError registration with invalid value from ConstraintViolation,
// as necessary for Hibernate Validator compatibility (non-indexed set path in field)
BindingResult bindingResult = (BindingResult) errors;
String nestedField = bindingResult.getNestedPath() + field;
if ("".equals(nestedField)) {
String[] errorCodes = bindingResult.resolveMessageCodes(errorCode);
bindingResult.addError(new ObjectError(
errors.getObjectName(), errorCodes, errorArgs, violation.getMessage()));
}
else {
Object rejectedValue = getRejectedValue(field, violation, bindingResult);
String[] errorCodes = bindingResult.resolveMessageCodes(errorCode, field);
bindingResult.addError(new FieldError(
errors.getObjectName(), nestedField, rejectedValue, false,
errorCodes, errorArgs, violation.getMessage()));
}
}
else {
// got no BindingResult - can only do standard rejectValue call
// with automatic extraction of the current field value
errors.rejectValue(field, errorCode, errorArgs, violation.getMessage());
}
}
catch (NotReadablePropertyException ex) {
throw new IllegalStateException("JSR-303 validated property '" + field +
"' does not have a corresponding accessor for Spring data binding - " +
"check your DataBinder's configuration (bean property versus direct field access)", ex);
}
}
}
}
驗(yàn)證錯(cuò)誤直接附加到DataBinder的private AbstractPropertyBindingResult bindingResult字段。
public class DataBinder implements PropertyEditorRegistry, TypeConverter {
/** Default object name used for binding: "target" */
public static final String DEFAULT_OBJECT_NAME = "target";
/** Default limit for array and collection growing: 256 */
public static final int DEFAULT_AUTO_GROW_COLLECTION_LIMIT = 256;
/**
* We'll create a lot of DataBinder instances: Let's use a static logger.
*/
protected static final Log logger = LogFactory.getLog(DataBinder.class);
@Nullable
private final Object target;
private final String objectName;
@Nullable
private AbstractPropertyBindingResult bindingResult;
@Nullable
private SimpleTypeConverter typeConverter;
此時(shí)它的值會(huì)在ModelAttributeMethodProcessor中檢索:
if (binder.getBindingResult().hasErrors()) {
if (isBindExceptionRequired(binder, parameter)) {
throw new BindException(binder.getBindingResult());
}
}
controller方法內(nèi)獲取BindingResult
需要注意的是系谐,要在控制器的方法中檢索BindingResult巾陕,必須將BindingResult實(shí)例直接放在經(jīng)過(guò)驗(yàn)證的對(duì)象之后。具體請(qǐng)看public String addArticle(@ModelAttribute(“article”) @Valid Article article, BindingResult result)纪他,BindingResult的實(shí)例將包含所有的驗(yàn)證錯(cuò)誤鄙煤。這時(shí),如果你在Article和BindingResult實(shí)例之間放置另一個(gè)對(duì)象(例如:HttpServletRequest request)茶袒,將拋出如下異常:
An Errors/BindingResult argument is expected to be declared immediately after the model attribute, the @RequestBody or the @RequestPart arguments to which they apply.
此錯(cuò)誤消息的內(nèi)容可以在org.springframework.web.method.annotation.ErrorsMethodArgumentResolver類中找到梯刚。此類用于從方法簽名中解析錯(cuò)誤實(shí)例。如果問(wèn)為什么用ErrorsMethodArgumentResolver來(lái)解析BindingResults薪寓?簡(jiǎn)單來(lái)說(shuō)亡资,這是由于BindingResult接口擴(kuò)展了Errors接口的緣故。所以预愤,兩者都可以用相同的參數(shù)解析器解決沟于。
/**
* Resolves {@link Errors} method arguments.
*
* <p>An {@code Errors} method argument is expected to appear immediately after
* the model attribute in the method signature. It is resolved by expecting the
* last two attributes added to the model to be the model attribute and its
* {@link BindingResult}.
*
* @author Rossen Stoyanchev
* @since 3.1
*/
public class ErrorsMethodArgumentResolver implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter parameter) {
Class<?> paramType = parameter.getParameterType();
return Errors.class.isAssignableFrom(paramType);
}
@Override
public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {
Assert.state(mavContainer != null, "Errors/BindingResult argument only supported on regular handler methods");
ModelMap model = mavContainer.getModel();
if (model.size() > 0) {
int lastIndex = model.size()-1;
String lastKey = new ArrayList<>(model.keySet()).get(lastIndex);
if (lastKey.startsWith(BindingResult.MODEL_KEY_PREFIX)) {
return model.get(lastKey);
}
}
throw new IllegalStateException(
"An Errors/BindingResult argument is expected to be declared immediately after the model attribute, " +
"the @RequestBody or the @RequestPart arguments to which they apply: " + parameter.getMethod());
}
}
從上面代碼可以看出,由于BindingResult的放置的位置 不正確植康,而導(dǎo)致驗(yàn)證過(guò)程失敗的方法其實(shí)很簡(jiǎn)單:
ModelMap model = mavContainer.getModel();
if (model.size() > 0) {
int lastIndex = model.size()-1;
String lastKey = new ArrayList<String>(model.keySet()).get(lastIndex);
if (lastKey.startsWith(BindingResult.MODEL_KEY_PREFIX)) {
return model.get(lastKey);
}
}
可以看到,它獲得用于構(gòu)建視圖部分的模型數(shù)據(jù)的ModelMap展懈。所要驗(yàn)證對(duì)象和BindingResult如果放置正確销睁,那么所要打印的日志應(yīng)該如下:
odel equals to {article=Article {text = }, org.springframework.validation.BindingResult.article=org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'article' on field 'text': rejected value []; codes [NotEmpty.article.text,NotEmpty.text,NotEmpty.java.lang.String,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [article.text,text]; arguments []; default message [text]]; default message [Text can't be empty]}
之后,將值放在ArrayList中存崖,并獲取最后一個(gè) entry key冻记。然后,檢查此鍵是否以org.springframework.validation.BindingResult開(kāi)頭(BindingResult 接口的常量值)来惧。如果是冗栗,該方法返回發(fā)現(xiàn)的Errors實(shí)例。否則供搀,將拋出一個(gè)IllegalStateException異常隅居。
public interface BindingResult extends Errors {
/**
* Prefix for the name of the BindingResult instance in a model,
* followed by the object name.
*/
String MODEL_KEY_PREFIX = BindingResult.class.getName() + ".";
/**
* Return the wrapped target object, which may be a bean, an object with
* public fields, a Map - depending on the concrete binding strategy.
*/
@Nullable
Object getTarget();
這篇文章講了Spring 驗(yàn)證的一些過(guò)程細(xì)節(jié)。它的第一部分介紹了驗(yàn)證流程葛虐,從@ModelAttribute開(kāi)始胎源,并以驗(yàn)證器集合結(jié)束。第二部分看了看基本的Spring驗(yàn)證器屿脐。在最后涕蚤,我們看到一個(gè)非常常見(jiàn)的bug宪卿,基于直接在驗(yàn)證對(duì)象之后放置BindingResult實(shí)例,并解釋了其中的原理所在万栅。
原文:Spring5源碼解析-使用@Valid進(jìn)行Spring驗(yàn)證
極樂(lè)科技:知乎專欄