SpringBoot从小白到大牛——第六节 Validator注解校验数据与自定义注解

一、Validator注解校验数据

目的是校验传入的参数是否符合要求

  1. 在pom.xml中加入hibernate-validator依赖
        <!--hibernate注解-->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.2.4.Final</version>
        </dependency>
  1. 在Dto或request中定义一个对象类UserRequest
@Data
@ToString
public class UserRequest implements Serializable {
    @NotBlank
    private String name;
    @NotBlank
    private String sex;
    @NotNull
    @Min(18)
    private Integer age;
}

其中的@NotBlank,@NotNull,@Min(18)都是注解校验,不为空,最小18。

  1. Controller中新建一个ValidateController,调用对象UserRequest,并且在前面加@Validated。
@RestController
public class ValidateController {

    private static final Logger log = (Logger) LoggerFactory.getLogger(ValidateController.class);

    private static final String prefix = "/validate";

    @RequestMapping(value = prefix+"/insert",method = RequestMethod.POST)
    //调用对象,并有修饰@Validated
    public BaseResponse insert(@RequestBody @Validated UserRequest userRequest, BindingResult result){
        BaseResponse baseResponse = new BaseResponse(StatusCode.Success);
        try {
            if(result.hasErrors()){
                baseResponse = new BaseResponse(StatusCode.Invalid_Params);
            }
            log.info("前端接收到的数据是:{}",userRequest);
        }catch (Exception e){
            baseResponse = new BaseResponse(StatusCode.Fail.getCode(),e.getMessage());
            e.printStackTrace();
        }
        return baseResponse;
    }
}

二、自定义注解

1.新建文件夹annotation
在里面新建一个接口

@Documented
@Constraint(validatedBy = SexValidation.class)
@Target({ElementType.FIELD,ElementType.ANNOTATION_TYPE,ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface SexAnnotation {
    String message() default "性别校验取值为:1=男,2=女";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

2.新建文件夹validate
在里面新建一个类

public class SexValidation implements ConstraintValidator<SexAnnotation,Integer> {
    Set<Integer> sexArr;

    @Override
    public void initialize(SexAnnotation constraintAnnotation) {
        sexArr = new HashSet<Integer>();
        sexArr.add(1);
        sexArr.add(2);
    }

    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        if(sexArr.contains(value)){
            return true;
        }else{
            return false;
        }

    }
}

3.使用时,在用户对象UserRequest的sex属性前使用SexAnnotation

    @SexAnnotation
    private Integer sex;

题外
CRUD:create,retrieve,update,delete,用于描述软件系统中database或持久层的基本操作

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值