🧑🎓 个人主页:花棉袄
📖 本章内容:【JRS303-数据校验】
✍🏻 版权: 本文由【花棉袄】原创💝在CSDN首发💝需要转载请联系博主
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-validationartifactId>
dependency>
javax.validation.constraints
包下🌳 @NotNull
🌳 @NotEmpty
集合长度的计算
Map (map size is evaluated)
map长度的计算
Array (array length is evaluated)
数组长度的计算
🌳 @NotBlank
🌳 @Valid
public R save(@Valid @RequestBody BrandEntity brand, BindingResult result){}
@Data
public class Student {
@NotEmpty(message ="姓名不能为空")
private String name;
}
@RestController
public class TestController {
@RequestMapping("/test")
public Result test(@Valid @RequestBody Student student, BindingResult result) {
String name = student.getName();
HashMap<String, Object> map = new HashMap<>();
map.put("name",name);
map.put("errors",result.getFieldErrors());
return Result.ok(map,"数据校验");
}
}
{
"name":""
}
{
"code": 200,
"msg": "数据校验",
"data": {
"name": "",
"errors": [
{
"codes": [
"NotEmpty.student.name",
"NotEmpty.name",
"NotEmpty.java.lang.String",
"NotEmpty"
],
"arguments": [
{
"codes": [
"student.name",
"name"
],
"arguments": null,
"defaultMessage": "name",
"code": "name"
}
],
"defaultMessage": "姓名不能为空",
"objectName": "student",
"field": "name",
"rejectedValue": "",
"bindingFailure": false,
"code": "NotEmpty"
}
]
}
}
@RestController
public class TestController {
@RequestMapping("/test")
public Result test(@Valid @RequestBody Student student, BindingResult result) {
String name = student.getName();
Map<String, String> map = new HashMap<>();
map.put("name", name);
if (result.hasErrors()) {
//1.获取错误的校验结果
result.getFieldErrors().forEach((item) -> {
//2.获取发生错误时的message
String message = item.getDefaultMessage();
//3.获取发生错误的字段
String field = item.getField();
map.put(field, message);
});
return Result.fail(map, "数据校验");
} else {
return Result.ok(map);
}
}
}
{
"name":""
}
{
"code": 500,
"msg": "数据校验",
"data": {
"name": "姓名不能为空"
}
}
@Slf4j
@RestControllerAdvice(basePackages = "com.michale.jrs303.controllers")
public class FireflyMallExceptionControllerAdvice {
/**
* 处理数据校验问题
* @param e
* @return
*/
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public Result handleVaildException(MethodArgumentNotValidException e) {
log.error("数据校验出现问题:{},异常类型:{}", e.getMessage(), e.getClass());
BindingResult bindingResult = e.getBindingResult();
Map<String, String> errorMap = new HashMap();
bindingResult.getFieldErrors().forEach((fieldError) -> {
errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
});
return Result.fail(errorMap, "数据校验出现问题");
}
/**
* 处理其他异常
* @param throwable
* @return
*/
@ExceptionHandler(value = Throwable.class)
public Result handleException(Throwable throwable) {
return Result.fail();
}
}
@RequestMapping("/testException")
public Result testException(@Valid @RequestBody Student student) {
String name = student.getName();
Map<String, String> map = new HashMap<>();
map.put("name", name);
return Result.ok(map);
}
{
"name":"",
}
{
"code": 500,
"msg": "数据校验出现问题",
"data": {
"name": "姓名不能为空"
}
}
/**
* @Author 天才小狐狸
* @Data 2022/8/11 2:03
* @Description 姓名校验分组
*/
public interface NameGroup {
}
/**
* @Author 天才小狐狸
* @Data 2022/8/11 2:04
* @Description 年龄校验分组
*/
public interface AgeGroup {
}
@Data
public class Student {
@NotEmpty(message ="姓名不能为空",groups = NameGroup.class)
private String name;
@NotEmpty(message ="绰号不能为空",groups = NameGroup.class)
private String nickName;
@Min(value = 18,message = "年龄下限不能低于18岁" ,groups = AgeGroup.class)
private String age;
@Max(value = 60,message = "年龄上限不能超过60岁" ,groups = AgeGroup.class)
private String retireAge;
}
@RequestMapping("/testGroup")
public Result testGroup(@Validated(NameGroup.class) @RequestBody Student student) {
String name = student.getName();
String nickName = student.getNickName();
String age = student.getAge();
String retireAge = student.getRetireAge();
Map<String, String> map = new HashMap<>();
map.put("name", name);
map.put("nickname", nickName);
map.put("age", age);
map.put("retireAge", retireAge);
return Result.ok(map);
}
{
"name":"",
"nickName":"",
"age":"17",
"retireAge":"66"
}
{
"code": 500,
"msg": "数据校验出现问题",
"data": {
"nickName": "绰号不能为空",
"name": "姓名不能为空"
}
}
@RequestMapping("/testGroup")
public Result testGroup(@Validated(AgeGroup.class) @RequestBody Student student) {
String name = student.getName();
String nickName = student.getNickName();
String age = student.getAge();
String retireAge = student.getRetireAge();
Map<String, String> map = new HashMap<>();
map.put("name", name);
map.put("nickname", nickName);
map.put("age", age);
map.put("retireAge", retireAge);
return Result.ok(map);
}
{
"name":"",
"nickName":"",
"age":"17",
"retireAge":66
}
{
"code": 500,
"msg": "数据校验出现问题",
"data": {
"retireAge": "年龄上限不能超过60岁",
"age": "年龄下限不能低于18岁"
}
}
@Documented
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
public @interface ListValue {
// 使用该属性去Validation.properties中取
String message() default "{com.atguigu.common.valid.ListValue.message}";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
int[] value() default {};
}
com.firefly.common.valid.ListValue.message=必须提交指定的值 [0,1]
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.HashSet;
import java.util.Set;
/**
* @author Michale @EMail:firefly@163.com
* @Date: 2022/1/8 19:23
* @Name ListValueConstraintValidator
* @Description:
*/
public class ListValueConstraintValidator implements ConstraintValidator<ListValue, Integer> {
private Set<Integer> set = new HashSet<>();
@Override
public void initialize(ListValue constraintAnnotation) {
//获取注解允许的值
int[] value = constraintAnnotation.value();
for (int i : value) {
set.add(i);
}
}
@Override
public boolean isValid(Integer value, ConstraintValidatorContext context) {
//判断传入的值是否在满足允许的值
boolean b = set.contains(value);
return b;
}
}
@Constraint(validatedBy = { ListValueConstraintValidator.class})
一个校验注解可以匹配多个校验器
@ListValue(value = {0,1},groups = {AgeGroup.class,MyJRS303Group.class})
private Integer gender;
{
"gender":"3"
}
{
"code": 500,
"msg": "数据校验出现问题",
"data": {
"gender": "必须提交指定的值 [0,1]"
}
}