spring boot使用自定义注解及@Validated进行自定义校验

 使用@Validate进行参数校验,spring boot 无需在导入其他maven坐标

创建实体测试:

@Data
public class Student {

    @NotNull(message = "名字不能为空")
    private String name;

    @NotBlank(message = "性别不能为空")
    private String sex;

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                '}';

    }
}

 创建全局异常对校验异常的返回格式做处理:

 

@ControllerAdvice
public class ApiException {

    /**
     * 捕捉全局所有的异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Map errorHandler(Exception e) {
        System.out.println(e);
        Map result = new HashMap();
        result.put("code",1);
        result.put("msg",e.getMessage());
        return result;
    }

    /**
     * 仅仅捕捉校验所产生的异常
     * @param exception
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public Map errorHandler(MethodArgumentNotValidException exception) {
        System.out.println(exception);
        Map resultMap = new HashMap();
        // 对校验异常返回的格式做出想要的返回结果
        FieldError fieldError = exception.getBindingResult().getFieldError();
        resultMap.put("code",1);
        resultMap.put("msg",fieldError.getDefaultMessage());
        return resultMap;
    }
}

  构建测试controller:

  

@Controller
public class ValidataController {

    @RequestMapping(value = "/testValid",method = RequestMethod.POST)
    @ResponseBody
    public Map testValid (@RequestBody @Validated Student student) {
        System.out.println(student.toString());
        HashMap result = new HashMap();
        result.put("code",0);
        result.put("msg","success");
        return result;
    }
}

 开始构建测试条件:

 spring boot使用自定义注解及@Validated进行自定义校验_第1张图片

 测试结果:

spring boot使用自定义注解及@Validated进行自定义校验_第2张图片

备注: @NotNull 只需要不为null 即可,比如 “” 是可以的, @NotBlank  “” 不可以,但是 NotBlank和 NotEmpty 都是用在字符串上面,而NotNull则都可以,如:Integer、Date 、LocalDateTime等

 但是在有些情况下,官方提供的这些校验方式并不能满足我们的需求,这时就需要我们自己定义一套校验方式,进行自定义校验

 首先我们需要创建一个自定义注解,下面就在student 上面加上一个属性电话作为实例操作

 

@Data
public class Student {

    @NotNull(message = "名字不能为空")
    private String name;

    @NotBlank(message = "性别不能为空")
    private String sex;

    @Phone
    private String phone; // 对电话格式自定义注解

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", phone='" + phone + '\'' +
                '}';

    }
}

  创建自定义注解Phone

  

@Documented
@Target({ElementType.PARAMETER, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = PhoneValid.class)
public @interface Phone {

    String message() default "电话格式错误";

    Class[] groups() default {};

    Class[] payload() default {};
}

  创建实现自定义注解Phone的类:

  

public class PhoneValid implements ConstraintValidator {


    @Override
    public void initialize(Phone constraintAnnotation) {

    }

    @Override
    public boolean isValid(String o, ConstraintValidatorContext constraintValidatorContext) {
        if(!StringUtils.isEmpty(o)) {
            return isMobile(o);
        }else{
            return false;
        }
    }

    public static boolean isMobile(String str) {
        Pattern p = null;
        Matcher m = null;
        boolean b = false;
        String s2="^[1](([3|5|8][\\d])|([4][4,5,6,7,8,9])|([6][2,5,6,7])|([7][^9])|([9][1,8,9]))[\\d]{8}$";// 验证手机号
        if(!StringUtils.isEmpty(str)){
            p = Pattern.compile(s2);
            m = p.matcher(str);
            b = m.matches();
        }
        return b;
    }
}

  开始测试:

  spring boot使用自定义注解及@Validated进行自定义校验_第3张图片

  测试结果:

  

  可见自定义注解校验生效

   温馨提示:

   调用方在调用处不能捕捉异常,也就是不能 try....catch...   若捕捉了异常,就会使异常不会抛出,因而自定义的全局异常捉不住异常,

   

 

  

你可能感兴趣的:(spring boot使用自定义注解及@Validated进行自定义校验)