1、maven坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<version>3.0.1</version>
</dependency>
2、校验规则
3、定义好校验规则还需要开启校验,在controller方法中添加@Validated注解
如下
@PostMapping
@ResponseBody
public CourseBaseInfoDto createCourse(@RequestBody @Validated AddCourseDto addCourseDto){
Long companyId = 22L;
CourseBaseInfoDto course = courseBaseService.createCourse(companyId,addCourseDto);
return course;
}
4、添加规则在实体类上面
package com.xuechengpluscontent.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
import java.math.BigDecimal;
/**
* @description 添加课程dto
* @author Mr.M
* @date 2022/9/7 17:40
* @version 1.0
*/
@Data
@ApiModel(value="AddCourseDto", description="新增课程基本信息")
public class AddCourseDto {
@NotEmpty(message = "课程名称不能为空666")
@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 = "课程介绍")
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;
}
5、编写统一异常处理类
@ResponseBody
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public RestErrorResponse ValidException(MethodArgumentNotValidException e){
BindingResult bindingResult = e.getBindingResult();
StringBuffer errMsg=new StringBuffer();
List<FieldError> fieldErrors = bindingResult.getFieldErrors();
for (FieldError fieldError : fieldErrors) {
errMsg.append(fieldError.getDefaultMessage());
}
log.info(errMsg.toString());
System.out.println(errMsg.toString());
return new RestErrorResponse(errMsg.toString());
}
使用JSR303校验必须引用MethodArgumentNotValidException异常
使用步骤详解如下
getBindingResult()方法是用来获取存起来的异常信息
使用StringBuffer来存储异常信息用来返回
bindingResult.getFieldErrors()获取字段错误的集合然后全部存储到StringBuffer中
最后返回