一 引入Maven
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
二 在对应的Controller的添加 @Validated 注解![](https://img-blog.csdnimg.cn/direct/1ec04c86080449ddac9ae90a55168691.png)
如果返回是 对象 还需要在对应的参数前添加 @Valid 注解
三在对应的实体类添加验证规则
@Null | 检查该字段为空 |
@NotNull | 不能为null |
@NotBlank | 不能为空,常用于检查空字符串 |
@NotEmpty | 不能为空,多用于检测list是否size是0 |
@Max | 该字段的值只能小于或等于该值 |
@Min | 该字段的值只能大于或等于该值 |
@Past | 检查该字段的日期是在过去 |
@Future | 检查该字段的日期是否是属于将来的日期 |
检查是否是一个有效的email地址 | |
@Pattern(regex=,flag=) | 被注释的元素必须符合指定的正则表达式 |
@Range(min=,max=,message=) | 被注释的元素必须在合适的范围内 |
@Size(min=, max=) | 检查该字段的size是否在min和max之间,可以是字符串、数组、集合、Map等 |
@Length(min=,max=) | 检查所属的字段的长度是否在min和max之间,只能用于字符串 |
@AssertTrue | 用于boolean字段,该字段只能为true |
@AssertFalse | 该字段的值只能为false |
如果 没有实体类在方法参数直接添加注解即可
如果默认不提供 message 错误提示则返回默认的
第四部 添加全局异常处理 将对应的验证异常返回返回给前端
package com.example.testdocker.config;
import jakarta.validation.ConstraintViolationException;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.ErrorResponse;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
@ResponseBody
@ControllerAdvice
public class GlobalExceptionHandler {
private final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
// 处理自定义异常
// @ExceptionHandler(CustomException.class)
// public ResponseEntity<ErrorResponse> handleCustomException(CustomException ex) {
// ErrorResponse error = new ErrorResponse(HttpStatus.BAD_REQUEST.value(), ex.getMessage());
// return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
// }
// 处理所有未被捕获的异常
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleAllExceptions(Exception ex) {
// ErrorResponse error = new ErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), "服务器内部错误");
log.error("服务器内部错误:{}",ex.getMessage());
return new ResponseEntity(Map.of("code", "500", "msg", "服务器内部错误"+ex), HttpStatus.INTERNAL_SERVER_ERROR);
}
// 处理实体校验异常,例如@Validated注解验证失败
@ExceptionHandler(ConstraintViolationException.class)
public ResponseEntity<ErrorResponse> handleValidationExceptions(ConstraintViolationException ex) {
return new ResponseEntity(Map.of("code", "500", "msg", getErrorMap(ex)), HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ErrorResponse> handleValidationExceptions(MethodArgumentNotValidException ex) {
return new ResponseEntity(Map.of("code", "500", "msg", getErrorMap(ex)), HttpStatus.BAD_REQUEST);
}
/**
* 获取验证失败错误信息
* @param ex
* @return
*/
private Map<String, String> getErrorMap(Exception ex) {
if(ex instanceof MethodArgumentNotValidException exception)
{
Map<String, String> errormap = new HashMap<>();
exception.getBindingResult().getAllErrors().forEach(error -> {
if (error instanceof FieldError) { // 确保转换安全
FieldError fieldError = (FieldError) error;
// 获取字段名称和错误消息
errormap.put(fieldError.getField(), fieldError.getDefaultMessage());
}
});
return errormap;
}
else if(ex instanceof ConstraintViolationException exception)
{
Map<String, String> errormap = new HashMap<>();
exception.getConstraintViolations().forEach(error -> {
// 获取字段名称和错误消息
errormap.put(error.getPropertyPath().toString(), error.getMessage());
});
return errormap;
}
throw new RuntimeException("不适用的异常类型"+ex);
}
}
到此就已经可以了