怎么在春季启动项目中利用jsr - 380进行校验

  介绍

怎么在春季启动项目中利用jsr - 380进行校验?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

介绍

<代码> jsr - 380> 的升级版,在春天引导中可以基于它优雅实现参数校验。

& lt; !——更多的在

示例

在没有使用jsr - 380 <代码> 之前,我们一般都会将参数校验硬编码在 <代码>控制器类中,示例:

public  Result 添加(@RequestBody  User 用户){   如果才能(StringUtils.isBlank (user.getName ())) {   ,,,return  Result.error(“用户名不能为空“);   ,,}//,才能……   }

而使用jsr - 380 <代码> 只需要通过添加对应的注解即可实现校验,示例:

@ data   public  class 用户{   @NotBlank才能   private 才能;String 名称;   private 才能;Integer 年龄;   } public  Result 注册(@Validated  @RequestBody  User 用户){//,才能……   }

这样看起来代码是不是清爽了很多,只需要在需要校验的字段上加上对应的校验注解,然后对需要校验的地方加上<代码> @Validated 注解,然后框架就会帮我们完成校验。

通过全局异常自定义错误响应

框架校验失败之后会抛出异常,需要捕获这个异常然后来自定义校验不通过的错误响应,这里直接贴代码,兼容<代码> @RequestBody ,<代码> @ModelAttribute ,<代码> @RequestParam 三种入参的校验:

@ControllerAdvice   public  class  GlobalExceptionHandler  {      @ExceptionHandler才能(value =, {MethodArgumentNotValidException.class, BindException.class})   public 才能;ResponseEntity< Result>, methodArgumentNotValidHandler (HttpServletRequest 请求,Exception  e), {   ,,,BindingResult  bindingResult;   ,,,if  (e  instanceof  MethodArgumentNotValidException), {   ,,,,,//@RequestBody参数校验   ,,,,,bindingResult =, ((MethodArgumentNotValidException), e) .getBindingResult ();   ,,,},{else    ,,,,,//@ModelAttribute参数校验   ,,,,,bindingResult =, ((BindException), e) .getBindingResult ();   ,,,}   ,,,FieldError  FieldError =, bindingResult.getFieldError ();   ,,,return  ResponseEntity.ok (Result.fail (Result.CODE_PARAMS_INVALID,,“[,, +, fieldError.getField (), +,“]”, +, fieldError.getDefaultMessage ()));   ,,}//@RequestParam才能参数校验   @ExceptionHandler才能(value =, {ConstraintViolationException.class, MissingServletRequestParameterException.class})   public 才能;ResponseEntity< Result>, constraintViolationHandler (Exception  e), {   ,,,String ;   ,,,String 味精;   ,,,if  (e  instanceof  ConstraintViolationException), {   ,,,,,ConstraintViolation<?祝辞,constraintViolation =, ((ConstraintViolationException), e) .getConstraintViolations () .stream () .findFirst () . get ();   ,,,,,List, pathList =, StreamSupport.stream (constraintViolation.getPropertyPath () .spliterator(),,假)   ,,,,,,,,,.collect (Collectors.toList ());   ,,,,,field =, pathList.get (pathList.size(),安康;1). getname ();   ,,,,,msg =, constraintViolation.getMessage ();   ,,,},{else    ,,,,,//,这个不是JSR标准返回的异常,要自定义提示文本   ,,,,,field =, ((MissingServletRequestParameterException), e) .getParameterName ();   ,,,,,msg =,“不能为空”;   ,,,}   ,,,return  ResponseEntity.ok (Result.fail (Result.CODE_PARAMS_INVALID,,“(“时间+大敌;;field  +,“]”, +, msg));   ,,}   }

然后再访问一下接口,可以看到错误提示已经按自定义的规范显示了:

怎么在春季启动项目中利用jsr - 380进行校验

可以看到都不需要写任何提示文本就可以完成校验和提示,上图的<代码>不能为空是框架内置的<代码> I18N 国际化支持,每个注解都内置相应的提示模板。

常用校验注解



注解描述@NotNull验证值不为null@AssertTrue验证值为true@Size验证值的长度介于最小和最大之间,可应用于字符串,收集、地图和数组类型@Min验证值不小于该值@Max验证值不大于该值验证字符串是有效的电子邮件地址@NotEmpty验证值不为null或空,可应用于字符串,收集、地图和数组类型@NotBlank验证字符串不为零并且不是空白字符@Positive验证数字为正数@PositiveOrZero验证数字为正数(包括0)@Negative验证数字为负数@NegativeOrZero验证数字为负数(包括0)@Past验证日期值是过去@PastOrPresent验证日期值是过去(包括现在)@Future验证日期值是未来@FutureOrPresent验证日期值是未来(包括现在)

怎么在春季启动项目中利用jsr - 380进行校验