在日常的接口开发中,为了防止非法参数对业务造成影响,经常需要对接口的参数做校验。例如登录的时候需要校验用户名密码是否为空,创建用户的时候需要校验邮件、手机号码格式是否准确。靠代码对接口参数一个个校验的话就太繁琐了,代码可读性极差。
Validator 框架就是为了解决开发人员在开发的时候少写代码,提升开发效率;Validator 专门用来进行接口参数校验,例如常见的必填校验,email 格式校验,用户名必须位于 6 到 12 之间等等…
依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.38</version>
</dependency>
</dependencies>
实体类
import lombok.Data;
import javax.validation.constraints.*;
import java.util.Date;
@Data
public class User4Validation {
@NotBlank(message = "主键不能为空")
private String id;
@NotBlank(message = "名字不能为空")
@Size(min = 2, max = 10, message = "名字字符长度必须为 2~10个")
private String name;
@Pattern(regexp = "^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$", message = "手机号格式错误")
private String phone;
@Email(message = "邮箱格式错误")
private String email;
@Past(message = "生日必须早于当前时间")
private Date birth;
@Min(value = 0, message = "年龄必须为 0~100")
@Max(value = 100, message = "年龄必须为 0~100")
private Integer age;
@PositiveOrZero
private Double score;
}
空值检查
| 注解 | 说明 |
|---|---|
| @NotBlank | 用于字符串,字符串不能为 null 也不能为空字符串 |
| @NotEmpty | 字符串同上,对于集合(Map,List,Set)不能为空,必须有元素 |
| @NotNull | 不能为 null |
| @Null | 必须为 null |
数值检查
| 注解 | 说明 |
|---|---|
| @DecimalMax(value)@DecimalMin(value) | 被注释的元素必须为数字,其值必须小于等于指定的值被注释的元素必须为数字,其值必须大于等于指定的值 |
| @Digits(integer, fraction) | 被注释的元素必须为数字,其值的整数部分精度为 integer,小数部分精度为 fraction |
| @Max(value)@Min(value) | 被注释的元素必须小于等于指定的值被注释的元素必须大于等于指定的值 |
| @Positive@PositiveOrZero | 被注释的元素必须为正数被注释的元素必须为正数或 0 |
| @Negative@NegativeOrZero | 被注释的元素必须为负数被注释的元素必须为负数或 0 |
布尔检查
| 注解 | 说明 |
|---|---|
| @AssertFalse @AssertTrue | 被注释的元素必须值为 false被注释的元素必须值为 true |
长度检查
| 注解 | 说明 |
|---|---|
| @Size(min, max) | 被注释的元素长度必须在 min 和 max 之间,可以是 String、Collection、Map、数组 |
日期检查
| 注解 | 说明 |
|---|---|
| @Future@FutureOrPresent | 被注释的元素必须是一个将来的日期被注释的元素必须是现在或者将来的日期 |
| @Past@PastOrPresent | 被注释的元素必须是一个过去的日期被注释的元素必须是现在或者过去的日期 |
其它检查
| 注解 | 说明 |
|---|---|
| 被注释的元素必须是电子邮箱地址 | |
| @Pattern(regexp) | 被注释的元素必须符合正则表达式 |
全局异常处理
枚举类定义状态码和状态信息:
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public enum ResultCode {
SUCCESS(200, "success"),
FAILED(400, "failed");
private final Integer code;
private final String msg;
}
定义一个公共的返回数据体:
import com.sunyu.springboot.constant.enums.ResultCode;
import lombok.Data;
@Data
public class ResultVo<T> {
// 状态码
private Integer code;
// 状态信息
private String msg;
// 数据
private T data;
// 成功,返回状态码、状态信息和数据
public ResultVo(T data) {
this.code = ResultCode.SUCCESS.getCode();
this.msg = ResultCode.SUCCESS.getMsg();
this.data = data;
}
// 失败,返回状态码、状态信息,不返回数据
public ResultVo(String msg) {
this.code = ResultCode.FAILED.getCode();
this.msg = msg;
this.data = null;
}
// 其它情况,返回指定状态码、状态信息和数据
public ResultVo(Integer code, String msg, T data) {
this.code = code;
this.msg = msg;
this.data = data;
}
}
定义一个业务异常类:
import com.sunyu.springboot.constant.enums.ResultCode;
import lombok.Getter;
@Getter
public class BusinessException extends RuntimeException {
private final ResultCode code;
public BusinessException(ResultCode code, String message) {
super(message);
this.code = code;
}
}
定义一个全局异常处理器:
import com.sunyu.springboot.entity.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@Slf4j
@RestControllerAdvice
@SuppressWarnings("rawtypes")
public class GlobalExceptionHandler {
@ExceptionHandler({BusinessException.class})
public ResultVo handleBusinessException(BusinessException e) {
return new ResultVo(e.getMessage());
}
@ExceptionHandler({MethodArgumentNotValidException.class})
public ResultVo handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
return new ResultVo(e.getMessage());
}
}
Controller
在 controller 的接口参数上加上 @Validated 注解,参数就需要根据你定义的规则来校验:
import com.sunyu.springboot.entity.User4Validation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ValidationController {
@PostMapping("/validation")
public User4Validation test(@RequestBody @Validated User4Validation user) {
return user;
}
}
该 MethodArgumentNotValidException 异常被全局异常处理后,会返回指定数据体:

1824

被折叠的 条评论
为什么被折叠?



