自定义注解解决参数校验

1.导入依赖

        
            org.springframework.boot
            spring-boot-starter-validation
        

2:在接口处添加注解 @Vaild

    @RequestMapping("/doLogin")
    public RespBean doLogin(@RequestBody @Valid LoginVo loginVo){
        log.info("{}",loginVo);
        return userService.doLogin(loginVo);
    }

3.在实体类添加注解规则

@Data
public class LoginVo {
    @NotNull
    @IsMobile //自定义注解
    private String mobile;
    @NotNull
    @Length(min = 32)
    private String password;
}

4.自定义注解声明

/**
 * 验证手机号
 * @author 刘宇浩
 * @since 1.0.0
 */
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = {IsMobileValidator.class})
public @interface IsMobile {

	boolean required() default true;

	String message() default "手机号码格式错误";

	Class[] groups() default { };

	Class[] payload() default { };
}

5.自定义校验规则

/**
 * 手机号码校验是否必填
 * @author 刘宇浩
 * @since 1.0.0
 */
public class IsMobileValidator implements ConstraintValidator {

	private boolean required = false;

	@Override
	public void initialize(IsMobile constraintAnnotation) {
		required = constraintAnnotation.required();
	}

	@Override
	public boolean isValid(String value, ConstraintValidatorContext context) {
		if (required){
			return ValidatorUtil.isMobile(value);
		}else {
			if (StringUtils.isEmpty(value)){
				return true;
			}else {
				return ValidatorUtil.isMobile(value);
			}
		}
	}
}
/**
 * 手机号码校验规则
 *
 * @author 刘宇浩
 * @since 1.0.0
 */
public class ValidatorUtil {

	private static final Pattern mobile_pattern = Pattern.compile("[1]([3-9])[0-9]{9}$");

	public static boolean isMobile(String mobile){
		if (StringUtils.isEmpty(mobile)){
			return false;
		}
		Matcher matcher = mobile_pattern.matcher(mobile);
		return matcher.matches();
	}
}

你可能感兴趣的:(java,后端)