ssm自定义校验注解

ssm自定义校验注解

在现在日常的后端开发中,我们常常会遇到需要将前端传递过来的参数进行校验的操作,比如说,某个值的非空判断,电话号码或身份证的格式判断等。而由springboot给我们提供的校验类中没有相关格式的判断,这样就需要我们自己通过代码去进行校验,下面由我来教大家怎样通过注解的方式进行相关属性的校验。下面以校验电话号码为例:

一、添加校验依赖:
首先我们需要在pom.xml文件中导入相关的校验依赖包。下面我使用了hutool里面的相关工具,所以也导入了hutool的依赖,

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
        
 <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.4</version>
        </dependency>

二、 添加@Valid注解
在controller类中对应方法请求的参数前加上@Valid注解
在这里插入图片描述
三、 在LoginVo请求参数的实体类中增加校验注解
下面@IsModile为我自定义的注解
在这里插入图片描述
四、 新建注解类
下面为我自定义的注解类,其中@Constraint(validatedBy = {IsMobileValidator.class}) 中对应的IsMobileValidator 为注解的实现类。required() 定义一个是否必填属性,如果为true 就是必填后面实现类会进行校验。default true 默认属性为true。

@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = {IsMobileValidator.class})
public @interface IsMobile {

    //ture为必填,false:非必填。默认为true
    boolean required() default true;

    //错误消息提示
    String message() default "手机号码格式错误!";

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

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

定义一个校验工具类
下面是一个电话号码的校验工具类,通过正则表达式进行手机号码的校验,使用者可以通过调用isMobile方法进行数据校验

public class ValidatorUtil {
    private static final Pattern model_pattern = Pattern.compile("(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\\d{8}$");

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

五、 新建一个注解的实现类
到这就已经全部完成了可以运行项目了,但是要想返回自己定义的参数,还需要配置全局异常

/**
 * IsMobile实现类
 */
public class IsMobileValidator implements ConstraintValidator<IsMobile, String> {

    private boolean required = false;

    /**
     * 初始化
     *
     * @param constraintAnnotation
     */
    @Override
    public void initialize(IsMobile constraintAnnotation) {
        required = constraintAnnotation.required();
    }

    /**
     *
     * @param value 判断的属性
     * @param constraintValidatorContext
     * @return
     */
    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        if (required) {
            return ValidatorUtil.isMobile(value);
        } else {
            if (StrUtil.isEmpty(value)) {
                return true;
            } else {
                return ValidatorUtil.isMobile(value);
            }
        }
    }
}

配置全局异常

@Data
@AllArgsConstructor
@NoArgsConstructor
public class GlobalException extends RuntimeException{

   private ResultEnum resultEnum;
}
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResultBean ExceptionHandler(Exception e) {
        if (e instanceof GlobalException) {
            GlobalException gex = (GlobalException) e;
            return ResultBean.fail(gex.getResultEnum());
        } else if (e instanceof BindException) {
            BindException bex = (BindException) e;
            ResultBean resultBean = ResultBean.fail(ResultEnum.ERROR_BIND_EXCEPTION_VALID);
            String msg = ResultEnum.ERROR_BIND_EXCEPTION_VALID.getMessage() + ":"
                    + bex.getBindingResult().getAllErrors().get(0).getDefaultMessage();
            resultBean.setMsg(msg);
            return resultBean;
        }
        return ResultBean.error();
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

遥不可及~~斌

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值