Spring Boot 数据校验

数据校验

1. @Valid注解实现字段校验

在使用 @Valid 注解之前,我们依然是要先引入依赖(如果是 Spring Boot 项目的话,就不需要专门引入依赖了,spring-boot-starter-web 已经帮我们引入好了)👇

<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>1.1.0.Final</version>
</dependency>
 
<dependency>
	<groupId>org.hibernate.validator</groupId>
	<artifactId>hibernate-validator</artifactId>
</dependency>

接下来我们对学生类和 Cotroller 进行一点小小的改造👇

package com.example.shiro.controller;

import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.Range;

import javax.validation.constraints.NotNull;

/**
 * 学生类
 * @description: Student
 * @create: 2022-02-16 11:12
 **/
public class Student {

    /**
     * 学生姓名
     */
    @NotNull(message = "Valid校验:请输入学生姓名!")
    @Length(message = "名称不能超过个 {max} 字符", max = 10)
    private String name;

    /**
     * 学生年龄
     */
    @NotNull(message = "Valid校验:请输入学生年龄")
    @Range(message = "年龄范围为 {min} 到 {max} 之间", min = 1, max = 100)
    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
复制代码
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * 模拟学生新增的过程
 * @description: StudentController
 * @create: 2022-02-16 11:19
 **/
@RestController
@RequestMapping("/student")
public class StudentController {

    @GetMapping("/add")
    public String add(@Valid Student student, BindingResult bindingResult){

        if(bindingResult.hasErrors()){
            return bindingResult.getAllErrors().get(0).getDefaultMessage();
        }
        return "添加成功";
    }
}
复制代码

我们可以看到,在 Cotroller 中我们增加了两部分内容,分别是 @Valid 和 BindingResult ,我们这里做一个简单的解释:

  • 给学生对象前增加上 @Valid 注解,就表示了我们需要对这个对象中的属性进行验证,验证的内容就是在学生类中增加的注解中的内容。
  • BindingResult 可以理解为 @Valid 注解的“老搭档”,BindingResult 作用就是在实体类校验信息后存储校验结果。

下面我们再试试校验有没有生效👇

在这里插入图片描述
在这里插入图片描述
我们可以看到,字段校验的结果和我们预期的一模一样,而且还让代码的可读性提高了一大截,是不是非常nice😄

最后再给大家总结一下实体类中常用的校验注解:

  • @Null:被注释的元素必须为null
  • @NotNull:被注释的元素不能为null
  • @AssertTrue:该字段只能为true
  • @AssertFalse:该字段的值只能为false
  • @Min(value):被注释的元素必须是一个数字,其值必须大于等于指定的最小值
  • @Max(value):被注释的元素必须是一个数字,其值必须小于等于指定的最大值
  • @DecimalMin(“value”):被注释的元素必须是一个数字,验证小数的最小值
  • @DecimalMax(“value”):被注释的元素必须是一个数字,验证小数的最大值
  • @Size(max,min):查该字段的size是否在min和max之间,可以是字符串、数组、集合、Map等
  • @Past:被注释的元素必须是一个过去的日期
  • @Future:被注释的元素必须是一个将来的日期
  • @Pattern(regexp = “[abc]”):被注释的元素必须符合指定的正则表达式。
  • @Email:被注释的元素必须是电子邮件地址
  • @Length(max=5,min=1,message=“长度在1~5”):检查所属的字段的长度是否在min和max之间,只能用于字符串
  • @NotEmpty:被注释的字符串必须非空
  • @Range:被注释的元素必须在合适的范围内
  • @NotBlank:不能为空,检查时会将空格忽略
  • @NotEmpty:不能为空,这里的空是指空字符串

整合优化

可以将校验的异常信息放在自定义断言中进行异常统一捕获返回

2. @Validated注解实现字段校验

  1. 使用方式

controller 层

@PostMapping("/saveUserInfo")
@ApiOperation("保存用户信息")
public BasicResultful saveUserInfo(@RequestBody @Validated UserInfoDTO userInfoDTO) {
    return userInfoService.saveOrUpdate(BeanUtil.copyProperties(userInfoDTO, UserInfo.class)) ? BasicResultful.success() : BasicResultful.fail();
}

DTO

@Data
@EqualsAndHashCode(callSuper = false)
public class UserInfoDTO {
    private static final long serialVersionUID = 1L;

    @ApiModelProperty(value = "自增ID")
    private BigInteger id;

    @ApiModelProperty(value = "名称")
    @NotBlank(message = "名称不能为空")
    private String name;

    @ApiModelProperty(value = "账号")
    @NotBlank(message = "账号不能为空")
    private String account;

    @ApiModelProperty(value = "密码")
    private String password;

    @ApiModelProperty(value = "有效状态")
    private Integer isValid;

    @ApiModelProperty(value = "描述")
    @NotBlank(message = "描述不能为空")
    private String description;

    @ApiModelProperty(value = "新增日期")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date createTime;

    @ApiModelProperty(value = "更新日期")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date updateTime;
}

统一异常处理

@RestControllerAdvice
public class SystemServiceHandler {

    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public BasicResultful handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder builder = new StringBuilder("校验失败:");
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            builder.append(fieldError.getField()).append(":").append(fieldError.getDefaultMessage()).append(",");
        }
        String message = builder.toString();
        return BasicResultful.fail(BasicResultEnum.Parameter_Verification_Failure, message);
    }

    @ExceptionHandler({ConstraintViolationException.class})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public BasicResultful handlerConstraintViolationException(ConstraintViolationException e) {
        return BasicResultful.fail(BasicResultEnum.Parameter_Verification_Failure, e.getMessage());
    }
}
posted @ 2022-06-23 09:45  Honlion  阅读(1052)  评论(0编辑  收藏  举报