1:在控制层上加上@Valid public String test(@Valid @RequestBody XXXReq req){} 2:在实体上加上@NotBlank @NotBlank(message = "不能为空") private String id; 3:新增个全部捕捉异常类 @ControllerAdvice public class GlobalController { /** 自定义验证异常 */ @ResponseBody @ExceptionHandler(MethodArgumentNotValidException.class) public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { Map<String, String> rsp = new HashMap<>(); rsp.put("result_msg", e.getBindingResult().getFieldError().getDefaultMessage()); rsp.put("result_code", "FAIL"); return JSON.toJSONString(rsp); } }
结果: