1:User
public class User {
private String name;
private String password;
getter and setter ...
}
2 :UserValidator
package com.zhao.validator;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.zhao.entity.User;
/**
*
* @author zhao.jw 2016年9月29日
*
*/
public class UserValidator implements Validator {
private static final int MINIMUM_PASSWORD_LENGTH = 6;
/**
* 判断该Validator是否能校验提供的Class的实例?
*/
public boolean supports(Class<?> clazz) {
/**
* 1:
* isAssignableFrom(Class<?> cls): 判定此 Class 对象所表示的类或接口与指定的 Class 参数所表示的类或接口是否相同,或是否是其超类或超接口。
* return User.class.isAssignableFrom(clazz);
* 2:
* equals(Object obj):指示其他某个对象是否与此对象“相等”。
* return User.class.equals(clazz);
*/
return User.class.isAssignableFrom(clazz);
}
/**
* 校验给定的对象,如果有校验失败信息,将其放入Errors对象
*/
public void validate(Object target, Errors errors) {
/**
* rejectIfEmptyOrWhitespace(Errors errors,String field,String errorCode):
* Reject the given field with the given error code if the value is empty or just contains whitespace.
* Parameters:
* errors - the Errors instance to register errors on
* field - the field name to check
* errorCode - the error code, interpretable as message key
*/
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "field.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "field.required");
User user=(User)target;
if (user.getPassword()!=null&&user.getPassword().trim().length()<MINIMUM_PASSWORD_LENGTH) {
/**
* rejectValue(String field,String errorCode,Object[] errorArgs,String defaultMessage):
* Register a field error for the specified field of the current object (respecting the current nested path, if any), using the given error description.
* Parameters:
* field - the field name (may be null or empty String)
* errorCode - error code, interpretable as a message key
* errorArgs - error arguments, for argument binding via MessageFormat (can be null)
* defaultMessage - fallback default message
*/
errors.rejectValue("password", "field.min.length",
new Object[]{Integer.valueOf(MINIMUM_PASSWORD_LENGTH)},
"The password must be at least ["+MINIMUM_PASSWORD_LENGTH+"] characters in length.");
}
}
}
Spring 提供了Validator接口用来进行对象的数据校验。Validator接口在进行数据校验的时候 会要求传入一个Errors对象,当有错误产生时会将错误信息放入该Errors对象。
org.springframework.validation.Validator:
supports(Class) - 判断该Validator是否能校验提供的Class的实例?
validate(Object, org.springframework.validation.Errors) - 校验给定的对象,如果有校验失败信息,将其放入Errors对象