First, the introduction of carrier package
maven address click away.
<!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-validator -->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.16.Final</version>
</dependency>
Second, create a validator package
1. Create a template return,
public class of ValidationResult { // test results for errors Private Boolean The hasErrors = to false ; // store map information error Private the Map <String, String> = errorMsgMap new new the HashMap <> (); public Boolean isHasErrors () { return The hasErrors; } public void setHasErrors ( Boolean The hasErrors) { the this .hasErrors = The hasErrors; } public the Map <String, String> getErrorMsgMap () { return errorMsgMap; } public void setErrorMsgMap (the Map <String, String> errorMsgMap) { the this .errorMsgMap = errorMsgMap; } // implementation of general information acquired by the format string error method results msg public String getErrMsg () { return StringUtils.join (errorMsgMap.values () .toArray (), "," ); } }
2. Create a class that implements checker
@Component public class ValidatorImpl implements InitializingBean { private Validator validator; // 实现效验方法并返回检验结果 public ValidationResult validate(Object bean){ final ValidationResult result= new ValidationResult(); Set<ConstraintViolation<Object>> constraintViolationSet=validator.validate(bean); if(constraintViolationSet.size()>0){ // 有错误 result.setHasErrors(true); constraintViolationSet.forEach(constraintViolation->{ String errMsg An = constraintViolation.getMessage (); String propertyName = constraintViolation.getPropertyPath () toString ();. . Result.getErrorMsgMap () PUT (propertyName, errMsg An); }); } return Result; } @Override public void afterPropertiesSet ( ) throws Exception { // the hibernate validtor initialized by the plant makes it instantiates the this .validator = Validation.buildDefaultValidatorFactory () getValidator ();. } }
Third, add annotations in the class javaBeanVo
public class UserModel { Private Integer the above mentioned id; @NotBlank (the Message = "User name can not be blank" ) Private String name; @NotNull (the Message = "sex can not fill" ) Private Byte Gender; @NotNull (the Message = "Age can not fill " ) @min (value = 0, the Message =" Age must be greater than 0 " ) @max (value = 150, the Message =" I wish you many happy returns, please contact officials (at the age of 150 years old, whichever cap) " ) Private Integer Age; @NotBlank (the Message = "phone number can not be empty" ) Private String Cellphone; private String registerMode; Private String thirdPartyId; @NotBlank (Message = "password is not blank" ) Private String encrptPassword; }
Fourth, practice
@Autowired ValidatorImpl validator; //方法内写 ValidationResult result=validator.validate(userModel); if (result.isHasErrors()){ throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,result.getErrMsg()); }