在接口处进行属性的安全校验时,使用@Validated 【import org.springframework.validation.annotation.Validated;】时,需要以下步骤:
1.引入pom依赖
<!-- springboot validation -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
2.构建全局异常捕获类
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
@ResponseBody
@ExceptionHandler(Exception.class)
public ResponseDTO execeptionHandler(Exception e){
log.error("error:",e);
// http 请求方式错误
if (e instanceof HttpRequestMethodNotSupportedException) {
return ResponseDTO.wrap(ResponseCodeConst.REQUEST_METHOD_ERROR);
}
// 参数类型错误
if (e instanceof TypeMismatchException) {
return ResponseDTO.wrap(ResponseCodeConst.ERROR_PARAM);
}
// json 格式错误
if (e instanceof HttpMessageNotReadableException) {
return ResponseDTO.wrap(ResponseCodeConst.JSON_FORMAT_ERROR);
}
// 参数校验未通过
if (e instanceof MethodArgumentNotValidException) {
List<FieldError> fieldErrors = ((MethodArgumentNotValidException) e).getBindingResult().getFieldErrors();
List<String> msgList = fieldErrors.stream().map(FieldError :: getDefaultMessage).collect(Collectors.toList());
return ResponseDTO.wrap(ResponseCodeConst.ERROR_PARAM, String.join(",", msgList));
}
if (e instanceof BusinessException) {
return ResponseDTO.wrap(ResponseCodeConst.SYSTEM_ERROR,e.getMessage());
}
return ResponseDTO.wrap(ResponseCodeConst.SYSTEM_ERROR);
}
}
3.dto对象中进行设置安全校验规则
javax.validation.constraints
eg:
@ApiModelProperty("手机号")
@NotBlank(message = "手机号不能为空")
private String phone;
4.接口处使用
@Validated进行校验
@PostMapping("/sys/user/register")
@ApiOperation(value = "用户注册")
public ResponseDTO register(@RequestBody @Validated UserRegisterDTO dto){
System.out.println(dto);
return ResponseDTO.succ();
}
5.实验截图
标签:return,验证,ResponseDTO,ResponseCodeConst,ERROR,wrap,Validated,属性 From: https://www.cnblogs.com/wlwtop/p/17674108.html