spring校验注解@valid和@validated重点获取校验消息
- @valid作用范围类,方法参数,成员变量。可以用来做嵌套校验。
- @validated作用范围类,方法参数。不可以用来做嵌套校验。可以分组,@valid不可以分组。
- 可以做一个全局捕获异常返回给前端校验消息
- 使用@valid注解
@ExceptionHandler(value = BindException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public ObjectRestResponse bindException(BindException e){
List<String> strings = new ArrayList<>();
List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
for (FieldError fieldError : fieldErrors) {
String defaultMessage = fieldError.getDefaultMessage();
strings.add(defaultMessage);
}
ObjectRestResponse response = new ObjectRestResponse();
response.setRel(false);
response.setMsg("参数错误");
response.setResult(strings);
return response;
}
- 使用@validated注解
@ExceptionHandler(value = ConstraintViolationException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public ObjectRestResponse parmeterNotValidException(ConstraintViolationException e){
String message = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining());
ArrayList<String> strings = new ArrayList<>();
strings.add(message);
ObjectRestResponse response = new ObjectRestResponse();
response.setRel(false);
response.setMsg("参数错误");
response.setResult(strings);
return response;
}
- 使用@notnull @notblank @max等等
@ExceptionHandler(value = BindException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public ObjectRestResponse bindException(BindException e){
List<String> strings = new ArrayList<>();
List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
for (FieldError fieldError : fieldErrors) {
String defaultMessage = fieldError.getDefaultMessage();
strings.add(defaultMessage);
}
ObjectRestResponse response = new ObjectRestResponse();
response.setRel(false);
response.setMsg("参数错误");
response.setResult(strings);
return response;
}
@ExceptionHandler(value = MethodArgumentNotValidException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public ObjectRestResponse methodArgumentNotValidException(MethodArgumentNotValidException e){
List<String> strings = new ArrayList<>();
List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
for (FieldError fieldError : fieldErrors) {
String defaultMessage = fieldError.getDefaultMessage();
strings.add(defaultMessage);
}
ObjectRestResponse response = new ObjectRestResponse();
response.setRel(false);
response.setMsg("参数错误");
response.setResult(strings);
return response;
}
}