前言
@Validation是一套帮助我们继续对传输的参数进行数据校验的注解,通过配置Validation可以很轻松的完成对数据的约束。
通过对DTO中实体类的约束,可以大大增加代码的简洁性。
错误的状态码
返回的响应码推荐使用400 bad request.
参数注解含义
实体类
/**
* @author: wangning
* @date: 2024/1/2 15:58
*/
@Data
public class UserDTO {
@NotNull(message = "用户id不能为空", groups = GroupAdd.class)
private Integer id;
@NotEmpty(message = "用户名add不能为空", groups = GroupAdd.class)
@NotEmpty(message = "用户名update不能为空", groups = GroupUpdate.class)
private String name;
@NotBlank(message = "邮箱不能为空", groups = {GroupAdd.class, GroupUpdate.class})
@Email(message = "邮箱格式不正确", groups = {GroupAdd.class, GroupUpdate.class})
// @Length(max = 6, message = "用户名长度不能超过6")
private String email;
}
依赖导入
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
</dependencies>
全局异常处理
/**
* @author: wangning
* @date: 2024/1/2 16:25
*/
@ControllerAdvice
@Slf4j
public class GlobalHandle {
// /**
// * 直接抛出异常,只能抛出第一个
// *
// * @param e
// * @return
// */
// @ExceptionHandler(MethodArgumentNotValidException.class)
// @ResponseBody
// @ResponseStatus(HttpStatus.OK)
// public String exception(MethodArgumentNotValidException e){
// log.error(e.getMessage());
// return e.getMessage();
// }
//
// /**
// * 可抛出所有异常
// *
// * @param exception
// * @return
// */
// @ResponseBody
// @ResponseStatus(HttpStatus.BAD_REQUEST)
// @ExceptionHandler(MethodArgumentNotValidException.class)
// public String exceptionHandler(MethodArgumentNotValidException exception){
// BindingResult result = exception.getBindingResult();
// StringBuilder stringBuilder = new StringBuilder();
// if (result.hasErrors()) {
// List<ObjectError> errors = result.getAllErrors();
// if (errors != null) {
// errors.forEach(p -> {
// FieldError fieldError = (FieldError) p;
// log.warn("Bad Request Parameters: dto entity [{}],field [{}],message [{}]",
// fieldError.getObjectName(),
// fieldError.getField(),
// fieldError.getDefaultMessage());
// stringBuilder.append(fieldError.getDefaultMessage());
// });
// }
// }
// return stringBuilder.toString();
// }
/**
* rds项目抽取
*
* @param ex
* @return
*/
@ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
@ResponseBody
@ResponseStatus(HttpStatus.OK)
public String bindException(BindException ex) {
List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
List<ObjectError> globalErrors = ex.getBindingResult().getGlobalErrors();
List<String> messages = new ArrayList<>();
//handle field errors
for (FieldError fieldError : fieldErrors) {
if (fieldError.isBindingFailure()) {
messages.add(fieldError.getField() + " property value convert failed");
} else {
messages.add(fieldError.getDefaultMessage());
}
}
//handle global errors, not sure about the existing situation right now, but leave it here for contingencies
for (ObjectError objectError : globalErrors) {
messages.add(objectError.getDefaultMessage());
}
log.error("[参数校验异常]: {}", StringUtils.join(messages, "; "), ex);
return Arrays.toString(messages.toArray());
}
// @ExceptionHandler(BindException.class)
// @ResponseBody
// @ResponseStatus(HttpStatus.OK)
// public String exception(BindException e){
// return e.getMessage();
// }
}
控制器
/**
* @author: wangning
* @date: 2024/1/2 16:00
*/
@RestController
public class UserController {
@PostMapping("/add")
public String add(@Validated(GroupAdd.class) @RequestBody UserDTO userDTO){
return "success";
}
@PostMapping("/update")
public String update(@Validated(GroupUpdate.class) @RequestBody UserDTO userDTO){
return "success";
}
}