1.引入pom
<!--validation验证-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
2.需要验证的实体类型加对应的注解(以非空判断为例)
@NotBlank(message = "单位名称不能为空")
private String orgName;
3.Controller对应方法里添加@Validated
public CommonResult createArmyOrg(@Validated @RequestBody ArmyOrg createArmyOrg) {
return armyOrgService.createArmyOrg(createArmyOrg);
}
4.验证结果,显示比较乱
5.添加统一异常返回类ApiError
/**
* @author zhangjianshan on 2020-10-23
*/
@Data
public class ApiError {
private Integer status = 400;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime timestamp;
private String message;
private ApiError() {
timestamp = LocalDateTime.now();
}
public static ApiError error(String message) {
ApiError apiError = new ApiError();
apiError.setMessage(message);
return apiError;
}
public static ApiError error(Integer status, String message) {
ApiError apiError = new ApiError();
apiError.setStatus(status);
apiError.setMessage(message);
return apiError;
}
}
6.添加全局异常处理ExceptionHandle
/**
* @author zhangjianshan on 2020-12-08
*/
@RestControllerAdvice
public class ExceptionHandle {
/**
* Validated
*
* @param e
* @return
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ApiError> exceptionHandler(MethodArgumentNotValidException e) {
return buildResponseEntity(ApiError.error(e.getBindingResult().getFieldError().getDefaultMessage()));
}
/**
* 重复
*
* @param e
* @return
*/
@ExceptionHandler(RepetitionException.class)
public ResponseEntity<ApiError> repetitionException(RepetitionException e) {
return buildResponseEntity(ApiError.error(e.getMessage()));
}
/**
* 统一返回
*/
private ResponseEntity<ApiError> buildResponseEntity(ApiError apiError) {
return new ResponseEntity<>(apiError, HttpStatus.valueOf(apiError.getStatus()));
}
}
7.再次验证结果