1.添加依赖

  1. <!--参数校验-->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-validation</artifactId>
  5. </dependency>

2.实体类属性添加标签

  1. @NotNull(message = "gameId不能为空")

3.Body参数校验

  1. @PostMapping("/tests")
  2. ResultData add(@RequestBody @Validated TestEntity testEntity){}

4.非Body参数校验

  1. @Validated
  2. public interface TestEntityApi {
  3. @GetMapping("/tests")
  4. ResultData get(@RequestParam @Size(min = 0, max = 1, message = "gameId大小异常") String gameId);
  5. }

5.增加全局异常处理类,用于更优雅的打印和返回参数异常相关信息

  1. import cn.hutool.core.collection.CollUtil;
  2. import cn.hutool.core.util.ObjectUtil;
  3. import cn.hutool.extra.servlet.ServletUtil;
  4. import cn.hutool.log.StaticLog;
  5. import com.cyou.yuffieserver3.common.exception.ClientException;
  6. import com.cyou.yuffieserver3.common.exception.ExcelException;
  7. import com.cyou.yuffieserver3.core.result.ResultData;
  8. import org.apache.tomcat.util.http.fileupload.FileUploadBase;
  9. import org.springframework.http.HttpStatus;
  10. import org.springframework.validation.ObjectError;
  11. import org.springframework.web.bind.MethodArgumentNotValidException;
  12. import org.springframework.web.bind.annotation.ExceptionHandler;
  13. import org.springframework.web.bind.annotation.ResponseBody;
  14. import org.springframework.web.bind.annotation.RestControllerAdvice;
  15. import javax.servlet.http.HttpServletRequest;
  16. import javax.validation.ConstraintViolationException;
  17. import java.sql.BatchUpdateException;
  18. import java.sql.SQLIntegrityConstraintViolationException;
  19. import java.util.ArrayList;
  20. /**
  21. * @author 冯铁城 [fengtiecheng@cyou-inc.com]
  22. * @date 2022-01-11 17:32:56
  23. * @describe:客户端异常处理
  24. */
  25. @RestControllerAdvice
  26. public class ClientExceptionHandler {
  27. /**
  28. * 请求体参数异常处理类
  29. *
  30. * @param request HTTP请求,用于获取请求URL
  31. * @param exception 捕获的异常
  32. * @return 异常信息
  33. */
  34. @ExceptionHandler(MethodArgumentNotValidException.class)
  35. @ResponseBody
  36. public ResultData handle(HttpServletRequest request, MethodArgumentNotValidException exception) {
  37. //1.定义异常结果集
  38. ArrayList<String> errorMessageList = CollUtil.newArrayList();
  39. //2.获取URL、请求方式以及异常信息
  40. if (!ObjectUtil.isNull(exception)) {
  41. if (!exception.getBindingResult().getAllErrors().isEmpty()) {
  42. //3.获取日志参数
  43. String ip = ServletUtil.getClientIP(request);
  44. String url = request.getRequestURI();
  45. String method = request.getMethod();
  46. for (ObjectError error : exception.getBindingResult().getAllErrors()) {
  47. String errorMessage = error.getDefaultMessage();
  48. StaticLog.error("[请求参数异常] IP=[{}] 请求方法=[{}] URL=[{}] 异常=[{}]", ip, method, url, errorMessage);
  49. errorMessageList.add(errorMessage);
  50. }
  51. }
  52. }
  53. //3.返回异常信息
  54. return ResultData.fail(HttpStatus.BAD_REQUEST.value(), errorMessageList);
  55. }
  56. /**
  57. * URL参数异常处理类
  58. *
  59. * @param request HTTP请求,用于获取请求URL
  60. * @param exception 捕获的异常
  61. * @return 异常信息
  62. */
  63. @ExceptionHandler(ConstraintViolationException.class)
  64. @ResponseBody
  65. public ResultData handle(HttpServletRequest request, ConstraintViolationException exception) {
  66. //1.获取URL、请求方式以及异常信息
  67. String ip = ServletUtil.getClientIP(request);
  68. String url = request.getRequestURI();
  69. String method = request.getMethod();
  70. String errorMessage = exception.getMessage();
  71. StaticLog.error("[请求参数异常] IP=[{}] 请求方法=[{}] URL=[{}] 异常=[{}]", ip, method, url, errorMessage);
  72. //2.返回异常信息
  73. return ResultData.fail(HttpStatus.BAD_REQUEST.value(), errorMessage);
  74. }
  75. }

6.常用标签说明

空检查

  1. @Null 验证对象是否为null
  2. @NotNull 验证对象是否不为null, 无法查检长度为0的字符串
  3. @NotBlank 检查约束字符串是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格.
  4. @NotEmpty 检查约束元素是否为NULL或者是EMPTY.

    Booelan检查

  5. @AssertTrue 验证 Boolean 对象是否为 true

  6. @AssertFalse 验证 Boolean 对象是否为 false

    长度检查

  7. @Size(min=, max=) 验证对象(Array,Collection,Map,String)长度是否在给定的范围之内

  8. @Length(min=, max=) 验证包含的string是否在min和max之间

    日期检查

  9. @Past 验证 Date 和 Calendar 对象是否在当前时间之前

  10. @Future 验证 Date 和 Calendar 对象是否在当前时间之后
  11. @Pattern 验证 String 对象是否符合正则表达式的规则

    数值检查

    建议使用在Stirng,Integer类型,不建议使用在int类型上,因为表单值为“”时无法转换为int,但可以转换为Stirng为””,Integer为null

  12. @Min 验证 Number 和 String 对象是否大等于指定的值

  13. @Max 验证 Number 和 String 对象是否小等于指定的值
  14. @DecimalMax 被标注的值必须不大于约束中指定的最大值. 这个约束的参数是一个通过BigDecimal定义的最大值的字符串表示.小数存在精度
  15. @DecimalMin 被标注的值必须不小于约束中指定的最小值. 这个约束的参数是一个通过BigDecimal定义的最小值的字符串表示.小数存在精度
  16. @Digits 验证 Number 和 String 的构成是否合法
  17. @Digits(integer=,fraction=) 验证字符串是否是符合指定格式的数字,interger指定整数精度,fraction指定小数精度。
  18. @Range(min=, max=) 检查注释值是否介于(包括)指定的最小值和最大值之间
  19. @Range(min=10000,max=50000,message=”range.bean.wage”)
  20. @Valid 递归的对关联对象进行校验, 如果关联对象是个集合或者数组,那么对其中的元素进行递归校验,如果是一个map,则对其中的值部分进行校验.(是否进行递归验证)
  21. @CreditCardNumber信用卡验证
  22. @Email 验证是否是邮件地址,如果为null,不进行验证,算通过验证。
  23. @ScriptAssert(lang= ,script=, alias=)
  24. @URL(protocol=,host=, port=,regexp=, flags=)