在 Spring Boot 中,可以使用 Validation 和国际化来实现对入参的校验。
| @NotNull | 验证字段值不能为 null |
| @NotEmpty | 验证字段值不能为 null 或空字符串 |
| @NotBlank | 验证字符串字段值不能为空、null,并且必须至少包含一个非空白字符 |
| @Size | 验证字符串、集合或数组的大小是否在指定范围内 |
| @Min | 验证数值字段值必须大于等于指定的最小值 |
| @Max | 验证数值字段值必须小于等于指定的最大值 |
| 验证字段值必须是有效的电子邮件地址格式 | |
| @Pattern | 验证字段值必须匹配指定的正则表达式模式 |
| @Past | 验证日期字段值必须是过去的日期 |
| @Future | 验证日期字段值必须是将来的日期 |
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-validation</artifactId>
- </dependency>




非空配置

长度配置



@NotBlank 注解用于验证字符串类型字段不为空或不为 null。如果验证失败,则使用 message 属性中定义的错误消息提示用户输入不能为空或 null 值。
@Length 注解用于验证字符串类型字段的长度是否符合指定的范围。如果验证失败,就会使用 message 属性中定义的错误消息提示用户输入的长度非法。
- /**
- * 学生姓名
- */
- @NotBlank(message = "{name.notBlank}")
- @Length(min = 2,max = 19,message="{name.length}")
- private String name;
@Validated 是 Spring Framework 提供的一个注解,用于在控制器方法级别或类级别上启用方法参数验证,以对请求参数进行验证。
@Valid 是 Java 标准库中的一个注解,它与 Bean Validation 规范(JSR 380)一起使用,用于启用对象级别验证。
- @RestController
- @RequestMapping("/test")
- @Validated
- public class TestController {
-
-
- @PostMapping("/user")
- public ResponseResult
user(@Valid @RequestBody Student student) { -
- return new ResponseResult<>("userToken");
- }
- }
这个类捕获参数异常
- import com.example.demo.util.HttpCodeEnum;
- import com.example.demo.util.ResponseResult;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.http.HttpStatus;
- import org.springframework.util.CollectionUtils;
- import org.springframework.validation.FieldError;
- import org.springframework.validation.ObjectError;
- import org.springframework.web.bind.MethodArgumentNotValidException;
- import org.springframework.web.bind.MissingServletRequestParameterException;
- import org.springframework.web.bind.annotation.ExceptionHandler;
- import org.springframework.web.bind.annotation.ResponseStatus;
- import org.springframework.web.bind.annotation.RestControllerAdvice;
-
- import javax.servlet.http.HttpServletRequest;
- import java.util.List;
-
- @RestControllerAdvice
- public class GlobalExceptionHandler {
-
- private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
-
- @Autowired
- private HttpServletRequest httpServletRequest;
-
- private final String sysError="系统出错";
-
- // get请求的对象参数校验异常
- @ResponseStatus(HttpStatus.BAD_REQUEST)
- @ExceptionHandler({MissingServletRequestParameterException.class})
- public ResponseResult bindExceptionHandler(MissingServletRequestParameterException e) {
- String requestURI = httpServletRequest.getRequestURI();
- log.error("请求地址'{}',get方式请求参数'{}'必传", requestURI,e.getParameterName());
- return ResponseResult.errorResult(HttpCodeEnum.SYSTEM_ERROR.getCode(), e.getMessage());
- }
- // post请求的对象参数校验异常
- @ResponseStatus(HttpStatus.BAD_REQUEST)
- @ExceptionHandler({MethodArgumentNotValidException.class})
- public ResponseResult methodArgumentNotValidHandler(MethodArgumentNotValidException e) {
- String requestURI = httpServletRequest.getRequestURI();
- log.error("请求地址'{}',post方式请求参数异常'{}'", requestURI, e.getMessage());
- List
allErrors = e.getBindingResult().getAllErrors(); - return ResponseResult.errorResult(HttpCodeEnum.SYSTEM_ERROR.getCode(), getValidExceptionMsg(allErrors));
- }
-
-
-
- private String getValidExceptionMsg(List
errors) { - if(!CollectionUtils.isEmpty(errors)){
- StringBuilder sb = new StringBuilder();
- errors.forEach(error -> {
- if (error instanceof FieldError) {
- sb.append(((FieldError)error).getField()).append(":");
- }
- sb.append(error.getDefaultMessage()).append(";");
- });
- String msg = sb.toString();
- msg = msg.substring(0, msg.length() -1);
- return msg;
- }
- return null;
- }
-
- }
name为空

name长度不符合

切换为英文
