1 、普通校验

添加依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-validation</artifactId>
  4. </dependency>

修改一下idea的配置,防止提示信息乱码
image.png
项目创建成功后,查看LocalValidatorFactoryBean类的源码,发现默认的ValidationMessageSource(校验出错时的提示文件)是resources目录下的ValidationMessages.properties 文件,如下:
image.png
因此在resource目录下创建ValidationMessages.properties文件,内容如下:

  1. city.cityname.notnull=城市名称必填
  2. city.cityInitial.notnull=城市首字母必填
  3. city.cityInitial.size=首字母长度为1

实体类中配置数据校验

  1. public class City implements Serializable {
  2. private static final long serialVersionUID = -40142021265771170L;
  3. /**
  4. * 主键 自增长
  5. */
  6. private Integer id;
  7. /**
  8. * 城市名称
  9. */
  10. @NotNull(message="{city.cityname.notnull}")
  11. private String cityName;
  12. /**
  13. * 城市名称拼音
  14. */
  15. private String cityNameSpell;
  16. /**
  17. * 城市首字母
  18. */
  19. @NotNull(message="{city.cityInitial.notnull}")
  20. // @DecimalMin(value = "1", message = "{city.cityInitial.size}")
  21. // @DecimalMax(value = "1", message = "{city.cityInitial.size}")
  22. @Length(min=1,max=1,message = "{city.cityInitial.size}")
  23. private String cityInitial;
  24. private Date createTime;
  25. private String creator;
  26. private Date operateTime;
  27. private String operator;

控制器中加入校验StudentController中加入@Validated:

  1. @PostMapping("add")
  2. public HttpResult add(@Validated City city){
  3. return HttpResult.ok("保存城市信息成功");
  4. }

默认返回的信息

  1. {
  2. "timestamp": "2020-07-27T07:08:41.933+0000",
  3. "status": 400,
  4. "error": "Bad Request",
  5. "errors": [
  6. {
  7. "codes": [
  8. "NotNull.city.cityName",
  9. "NotNull.cityName",
  10. "NotNull.java.lang.String",
  11. "NotNull"
  12. ],
  13. "arguments": [
  14. {
  15. "codes": [
  16. "city.cityName",
  17. "cityName"
  18. ],
  19. "arguments": null,
  20. "defaultMessage": "cityName",
  21. "code": "cityName"
  22. }
  23. ],
  24. "defaultMessage": "城市名称不允许为空",
  25. "objectName": "city",
  26. "field": "cityName",
  27. "rejectedValue": null,
  28. "bindingFailure": false,
  29. "code": "NotNull"
  30. }
  31. ],
  32. "message": "Validation failed for object='city'. Error count: 1",
  33. "path": "/city/add"
  34. }

使用BindingResult保存校验出错时的的信息 ,StudentController加入

  1. @PostMapping("/add")
  2. public HttpResult add(@Validated Student student, BindingResult result){
  3. List<String> errorList=new ArrayList<>();
  4. if(result.hasErrors()){
  5. List<ObjectError> list=result.getAllErrors();
  6. for(ObjectError objectError:list){
  7. errorList.add(objectError.getDefaultMessage());
  8. }
  9. //下面使用lambda表达式和上面的for作用一样
  10. // result.getAllErrors().forEach( objectError -> errorList.add(objectError.getDefaultMessage()));
  11. }
  12. if(!errorList.isEmpty()){
  13. return HttpResult.error(errorList);
  14. }
  15. return HttpResult.ok("保存城市信息成功");
  16. }

返回信息

  1. {
  2. "code": 1000,
  3. "msg": null,
  4. "data": [
  5. "首字母长度为1",
  6. "城市名称必填"
  7. ]}

2 全局异常处理类(BindException)

可以在controller方法中将BindingResult result参数进行删除,进行统一处理

  1. /**
  2. * 定义全局异常类
  3. * 全局异常控制类加入拦截
  4. */
  5. @RestControllerAdvice
  6. public class GlobalExceptionHandle {
  7. @ExceptionHandler(value = BindException.class)
  8. public HttpResult bindExceptionErrorHandler(BindException ex) throws Exception {
  9. List<String> errorList=new ArrayList<>();
  10. if(ex.hasErrors()){
  11. List<ObjectError> list=ex.getAllErrors();
  12. for(ObjectError objectError:list){
  13. errorList.add(objectError.getDefaultMessage());
  14. }
  15. // ex.getAllErrors().forEach( objectError -> errorList.add(objectError.getDefaultMessage()));
  16. }
  17. if(!errorList.isEmpty()){
  18. return HttpResult.error(errorList);
  19. }
  20. return HttpResult.error();
  21. }
  22. }

3 、常用注解

image.png

4 、全局异常处理类

  1. /**
  2. * 定义全局异常类
  3. * 全局异常控制类加入拦截
  4. */
  5. @RestControllerAdvice
  6. public class GlobalExceptionHandle {
  7. @ExceptionHandler(value = BindException.class)
  8. public HttpResult bindExceptionErrorHandler(BindException ex) throws Exception {
  9. List<String> errorList = new ArrayList<>();
  10. if (ex.hasErrors()) {
  11. List<ObjectError> list = ex.getAllErrors();
  12. for (ObjectError objectError : list) {
  13. errorList.add(objectError.getDefaultMessage());
  14. }
  15. //lambda 表达式写法,和上面的for循环一样
  16. // ex.getAllErrors().forEach( objectError -> errorList.add(objectError.getDefaultMessage()));
  17. }
  18. if (!errorList.isEmpty()) {
  19. return HttpResult.error(errorList);
  20. }
  21. return HttpResult.error();
  22. }
  23. // -----------------------Request------------------------------------------------
  24. @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
  25. @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
  26. public HttpResult handleMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
  27. return HttpResult.error("错误的请求方式");
  28. }
  29. @ExceptionHandler(MissingServletRequestParameterException.class)
  30. @ResponseStatus(HttpStatus.OK)
  31. public HttpResult handleMissingParameterException(MissingServletRequestParameterException e) {
  32. return HttpResult.error("参数缺失");
  33. }
  34. // ----------------------------data--------------------------------------
  35. @ExceptionHandler(DataAccessException.class)
  36. @ResponseStatus(HttpStatus.OK)
  37. public HttpResult handlerDataAccessException(DataAccessException e) {
  38. return HttpResult.error(31000, "数据库异常");
  39. }
  40. @ExceptionHandler(EmptyResultDataAccessException.class)
  41. @ResponseStatus(HttpStatus.OK)
  42. public HttpResult handleDataEmptyException(EmptyResultDataAccessException e) {
  43. return HttpResult.error("数据不存在");
  44. }
  45. @ExceptionHandler(DuplicateKeyException.class)
  46. @ResponseStatus(HttpStatus.OK)
  47. public HttpResult handleDataDualException(DuplicateKeyException e) {
  48. return HttpResult.error("数据重复插入");
  49. }
  50. // @ExceptionHandler(MultipartException.class)
  51. // @ResponseStatus(HttpStatus.OK)
  52. // public HttpResult handlerMultipartException(Throwable ex) {
  53. // String message = "文件上传错误";
  54. // MultipartException mEx = (MultipartException) ex;
  55. // if (ex.getCause() != null) {
  56. // Throwable cause = ex.getCause().getCause();
  57. // if (cause instanceof SizeLimitExceededException) {
  58. // SizeLimitExceededException flEx = (FileUploadBase.SizeLimitExceededException) cause;
  59. // float permittedSize = flEx.getPermittedSize() / 1024 / 1024;
  60. // message = "文件大小超过" + permittedSize + "MB";
  61. // } else if (cause instanceof FileSizeLimitExceededException) {
  62. // FileSizeLimitExceededException flEx = (FileSizeLimitExceededException) mEx.getCause().getCause();
  63. // float permittedSize = flEx.getPermittedSize() / 1024 / 1024;
  64. // message = "文件大小超过" + permittedSize + "MB";
  65. // }
  66. // }
  67. //
  68. // return HttpResult.error(message);
  69. // }
  70. // ---------All--------------------------------
  71. @ExceptionHandler(Exception.class)
  72. @ResponseStatus(HttpStatus.OK)
  73. public HttpResult handlerException(Exception e) {
  74. return HttpResult.error(30000, "系统异常");
  75. }
  76. }