您现在的位置是:首页 >其他 >SpringBoot基于Hibernate Validator的JSR303校验网站首页其他

SpringBoot基于Hibernate Validator的JSR303校验

LongZheAPEX 2023-06-03 16:00:03
简介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)
    
风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。