SpringBoot基于Hibernate Validator的JSR303校验

  1. 加入依赖

       <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-validation</artifactId>
            </dependency>
    
  2. 在实体类的属性中使用注解设置参数校验

    @Data
    @ApiModel(value="AddCourseDto", description="新增课程基本信息")
    public class AddCourseDto {
    
     @NotEmpty(message = "课程名称不能为空")
     @ApiModelProperty(value = "课程名称", required = true)
     private String name;
    
     @NotEmpty(message = "适用人群不能为空")
     @Size(message = "适用人群内容过少",min = 10)
     @ApiModelProperty(value = "适用人群", required = true)
     private String users;
    
     @ApiModelProperty(value = "课程标签")
     private String tags;
    
     @NotEmpty(message = "课程分类不能为空")
     @ApiModelProperty(value = "大分类", required = true)
     private String mt;
    
     @NotEmpty(message = "课程分类不能为空")
     @ApiModelProperty(value = "小分类", required = true)
     private String st;
    
     @NotEmpty(message = "课程等级不能为空")
     @ApiModelProperty(value = "课程等级", required = true)
     private String grade;
    
     @ApiModelProperty(value = "教学模式(普通,录播,直播等)", required = true)
     private String teachmode;
    
     @ApiModelProperty(value = "课程介绍")
     @Size(message = "课程描述内容过少",min = 10)
     private String description;
    
     @ApiModelProperty(value = "课程图片", required = true)
     private String pic;
    
     @NotEmpty(message = "收费规则不能为空")
     @ApiModelProperty(value = "收费规则,对应数据字典", required = true)
     private String charge;
    
     @ApiModelProperty(value = "价格")
     private Float price;
     @ApiModelProperty(value = "原价")
     private Float originalPrice;
    
    
     @ApiModelProperty(value = "qq")
     private String qq;
    
     @ApiModelProperty(value = "微信")
     private String wechat;
     @ApiModelProperty(value = "电话")
     private String phone;
    
     @ApiModelProperty(value = "有效期")
     private Integer validDays;
    }
    
    
  3. 在controller方法参数中使用 @Validated使校验生效

    public CourseBaseInfoDto createCourseBase(@RequestBody @Validated AddCourseDto addCourseDto)
    
  4. 在全局异常中对JSR303错误信息解析

     //JSR303校验框架异常解析
        @ExceptionHandler(MethodArgumentNotValidException.class)
        @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
        public RestErrorResponse  methodArgumentNotValidException(MethodArgumentNotValidException exception){
    
            BindingResult bindingResult = exception.getBindingResult();
            //存储错误信息
            List<String> errors = new ArrayList<>();
            bindingResult.getFieldErrors().stream().forEach(item->{
                errors.add(item.getDefaultMessage());
            });
    
            //将list中的错误信息拼接起来
            String errMessage = StringUtils.join(errors, ",");
            //记录异常日志
            log.error("JSR303参数验证异常{}",exception.getMessage(),errMessage);
    
            //解析出异常信息
            RestErrorResponse restErrorResponse = new RestErrorResponse(errMessage);
            return restErrorResponse;
        }
    
  5. 多个接口共用一个模型类:分组校验 定义一些常用组

    /**
     * @version 1.0
     * @Author zhaozhixin
     * @Date 2023/4/17 23:49
     * @注释 用于分级校验,定义一些常用的组
     */
    public class ValidationGroups {
        public interface Insert{};
        public interface Update{};
        public interface Delete{};
    }
    
    
  6. 在模型类的属性的验证注解中增加groups属性:示例

     @NotEmpty(message = "课程名称不能为空",groups ={ValidationGroups.Insert.class} )
     @NotEmpty(message = "课程名称不能为空",groups ={ValidationGroups.Update.class} )
     @ApiModelProperty(value = "课程名称", required = true)
     private String name;
    
  7. 在接口的@Validated注解中指定是哪个组

    @PostMapping("/course")public CourseBaseInfoDto createCourseBase(@RequestBody @Validated(ValidationGroups.Insert.class) AddCourseDto addCourseDto)
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值