SpringBoot has a built-in Hibernate Validator as the checking framework, so as long as we have integrated SpringBoot, we can use Hibernate Validator to complete parameter checking.
Common Notes
- @Null: The commented property must be null;
- @NotNull: The commented property cannot be null;
- @AssertTrue: The commented property must be true;
- @AssertFalse: The commented property must be false;
- @Min: The commented property must be greater than or equal to its value;
- @Max: The commented property must be less than or equal to its value;
- @Size: The commented property must be between its min and max values;
- @Pattern: The commented property must conform to the regular expression defined by its regexp;
- @NotBlank: The commented string cannot be an empty string;
- @NotEmpty: The commented property cannot be empty;
- @Email: The commented property must conform to the mailbox format.
Where @NotNull, @NotEmpty,@NotBlank is different
- @NotNull is on the base type
- @NotEmpty is on a collection
- @NotBlank is on the String type
Implement parameter checking
Add a comment to the field of the vo object
import com.seckillproject.common.GenderValid; import javax.validation.constraints.Min; import javax.validation.constraints.NotBlank; /** * @Auther cj-ervin * @Date 2020/4/18 */ public class UserVo { private Integer id; @NotBlank(message = "Name cannot be empty") private String name; @Min(value = 0,message = "Age must not be less than 0") private Integer age; @NotBlank(message = "Mobile phone cannot be empty") private String telphone; @NotBlank(message = "Password cannot be empty") private String password; @NotBlank(message = "Authentication code cannot be empty") private String checkCode; }
Add @Validated and BindingResult to controller method entry
@ResponseBody @RequestMapping(value = "/register",method = RequestMethod.POST) public CommonReturn register(@Validated @RequestBody UserVo userVo , BindingResult bindingResult) throws BusinessException { //Verify Code if (!userVo.getCheckCode().equals(this.request.getSession().getAttribute(userVo.getTelphone()))){ throw new BusinessException(EnumBusinessError.PARAMETER_VALIDATION_ERROR.setErrorMsg("Verification Code Check Error")); } UserDto userDto = convertToUserDto(userVo); userService.register(userDto); return CommonReturn.success(null); }
Parameter checking with aop
/** * @Auther cj-ervin * @Date 2020/4/19 */ @Aspect @Component public class ParamValidator { @Pointcut("execution(public * com.seckillproject.controller.*.*(..))") public void paramValid(){ } @Around("paramValid()") public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable { Object[] args = joinPoint.getArgs(); for (Object obj:args) { if (obj instanceof BindingResult){ BindingResult bindingResult = (BindingResult) obj; if (bindingResult.hasErrors()){ FieldError fieldError = bindingResult.getFieldError(); if (fieldError != null){ return CommonReturn.fail(fieldError.getDefaultMessage()); }else{ return CommonReturn.fail(); } } } } return joinPoint.proceed(); } }
Now let's verify:
When the age input is less than 0, there will be a prompt.
Custom Notes
Sometimes the annotations provided by the framework do not meet our business needs, which is what we need to customize.
For example, if we want the gender gender field to be validated, we can only pass in 1 or 2, and passing in other values will prompt illegal parameters.
Definition Notes
@Target({ElementType.PARAMETER,ElementType.FIELD}) @Documented @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = GenderValidator.class) public @interface GenderValid { String[] value() default {}; String message() default ""; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
ValidateRules
/** * @Auther cj-ervin * @Date 2020/4/19 */ public class GenderValidator implements ConstraintValidator<GenderValid,Byte> { private String[] values; @Override public void initialize(GenderValid constraintAnnotation) { this.values = constraintAnnotation.value(); } @Override public boolean isValid(Byte aByte, ConstraintValidatorContext constraintValidatorContext) { boolean isValid = false; if(aByte==null){ //Use default value when state is empty return true; } for(int i=0;i<values.length;i++){ if(values[i].equals(String.valueOf(aByte))){ isValid = true; break; } } return isValid; } }
Use annotations inside vo objects
/** * @Auther cj-ervin * @Date 2020/4/18 */ public class UserVo { private Integer id; @NotBlank(message = "Name cannot be empty") private String name; @GenderValid(value = {"1","2"},message = "Please enter 1 or 2 for gender") private Byte gender; @Min(value = 0,message = "Age must not be less than 0") private Integer age; @NotBlank(message = "Mobile phone cannot be empty") private String telphone; @NotBlank(message = "Password cannot be empty") private String password; @NotBlank(message = "Authentication code cannot be empty") private String checkCode; }
Verification,
At this point, the parameter verification at the controller level has been completed.Data validation at the service or dao level can be accomplished with exception handling, which is described in a blog post.