验证注解
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<version>2.7.0</version>
</dependency>
-
dto数据传输对象中使用注解
-
使用该对象时,添加@Valid或者@Validated
# 例如控制层中
@PostMapping("/test")
public void test(@Valid @RequestBody User user){
...
}
- 全局配置返回错误信息
@RestControllerAdvice
@Slf4j
public class ExceptionResolver {
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = { MethodArgumentNotValidException.class})
public RetJson methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
return RetJson.fail(ResultCode.VALIDATE_FAILED.getCode(), "参数异常"+e.getBindingResult().getFieldError().getDefaultMessage());
}
}
- 控制层中直接方法错误信息
@PostMapping(value = "/updateUser")
public JSONResult updateUser(@Valid @RequestBody ResetPwdDTO resetPwdDTO, BindingResult result){
if (result.hasErrors()) {
StringBuilder sb = new StringBuilder();
for (ObjectError error : result.getAllErrors()) {
sb.append(error.getDefaultMessage());
}
log.error("参数错误:", sb);
return new JSONResult(40001, sb.toString());
} else {
User user = UserAssembler.ResetPwdDtoToUser(resetPwdDTO);
int i = userMapper.updateById(user);
return new JSONResult(i);
}
}