SpringBoot之自定义注解

直接代码

@IsMobile
private String mobile;

1. 定义自定义注解

@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = {IsMobileValidator.class}) // 这个类及时下面的那个类
public @interface IsMobile {

    boolean required() default true; //默认为true

    String message() default "(手机号码格式有误)"; //返回的消息

    Class<?>[] groups() default { };

    Class<? extends Payload>[] payload() default { };
}

2. 定义IsMobileValidator类

public class IsMobileValidator implements ConstraintValidator<IsMobile, String> {

    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); //ValidatorUtil.isMobile() 就是一个校验的方法
            }
        }
    }
}

3. 定义验证类 ValidatorUtil

public class ValidatorUtil {

    // 开头是1 后面跟了10个数字, 正则表达式
    private static final Pattern mobile_pattern = Pattern.compile("1\\d{10}");

    public static boolean isMobile(String src) {
        if (StringUtils.isEmpty(src)) {
            return false;
        }
        Matcher m = mobile_pattern.matcher(src);
        return m.matches();
    }
}
4. 自定义全局异常提示(其中Bind异常为上面自定义表单的异常) 可以加上其他的异常xxxException
@ControllerAdvice
@ResponseBody  // 这个注解是为了测试使用
public class GlobalExceptionHandler {
    
    @ExceptionHandler(value = Exception.class)
    public Result<String> exceptionHandler(HttpServletRequest request, Exception e) {
        
        if (e instanceof BindException) {
            BindException ex = (BindException)e;
            String message = ex.getAllErrors().get(0).getDefaultMessage(); // 获取第一个错误信息
            return Result.error(message);
        } else {
            return //详细的错误信息比如 e.printStackTrace(); 
        }
    }
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值