SpringBoot使用jsr303校验的实现

作者:guomz 时间:2022-04-21 04:02:39 

依赖添加


<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

一些较老版本的SpringBoot需要添加相关依赖,我使用的2.1.4发行版不用这个操作。

验证使用对象接收参数的情况


public class PointDeductSetRequest {
private Long id;
@NotBlank(message = "租户id为空")
private String tenantId;
private Integer status;
@NotNull
private Integer pointValue;
@NotNull
private Integer deductValue;
@NotBlank(message = "操作员id为空")
private String operator;
}

首先在需要验证的对象的对应字段上方加上校验注解,以下为一些常用注解:

  • @Null 限制只能为null

  • @NotNull 限制必须不为null

  • @AssertFalse 限制必须为false

  • @AssertTrue 限制必须为true

  • @DecimalMax(value) 限制必须为一个不大于指定值的数字

  • @DecimalMin(value) 限制必须为一个不小于指定值的数字

  • @Digits(integer,fraction) 限制必须为一个小数,且整数部分的位数不能超过integer,小数部分的位数不能超过fraction

  • @Future 限制必须是一个将来的日期

  • @Max(value) 限制必须为一个不大于指定值的数字

  • @Min(value) 限制必须为一个不小于指定值的数字

  • @Past 限制必须是一个过去的日期

  • @Pattern(value) 限制必须符合指定的正则表达式

  • @Size(max,min) 限制字符长度必须在min到max之间

  • @Past 验证注解的元素值(日期类型)比当前时间早

  • @NotEmpty 验证注解的元素值不为null且不为空(字符串长度不为0、集合大小不为0)

  • @NotBlank 验证注解的元素值不为空(不为null、去除首位空格后长度为0),不同于@NotEmpty,@NotBlank只应用于字符串且在比较时会去除字符串的空格

  • @Email 验证注解的元素值是Email,也可以通过正则表达式和flag指定自定义的email格式


@RequestMapping(value = "/deduct", method = RequestMethod.POST)
public BusinessResponse setPointDeduct(@RequestBody @Valid PointDeductSetRequest request){
 pointDeductService.setPointDeductRule(request);
 return new BusinessResponse(ResponseEnum.OK);
}

之后在controller方法的对象参数前加@Valid注解。

校验使用单个参数接受的情况


@RequestMapping(value = "/deduct", method = RequestMethod.GET)
public PageResponse<TPointDeduct> getPointDeductList(@RequestParam(value = "page", required = false) Integer page,
@RequestParam(value = "pageSize", required = false) Integer pageSize,
@RequestParam(value = "tenantId", required = false) @NotBlank(message = "租户id为空") String tenantId,
@RequestParam(value = "status", required = false) Integer status){
 PageResponse<TPointDeduct> response = pointDeductService.getPointDeductList(page, pageSize, tenantId, status);
response.setCodeMsg(ResponseEnum.OK);
return response;
}

首先需要在controller类上加@Validated注解,之后在方法中需要校验的参数前加上对应的校验注解进行校验。

对校验产生的异常的捕获

定义全局异常处理类并用@ControllerAdvice标注,由于对象和单个参数因校验产生的异常类型不同,因此需要分别处理。

对于对象作为接收前端请求的情况,因校验产生的异常类型为MethodArgumentNotValidException,示例方法如下:


/**
* 捕获303对于body中的对象字段校验
* @param e
* @param request
* @return
*/@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
ResponseEntity<Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request){
 List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
if (fieldErrors != null && !fieldErrors.isEmpty()){
  String message = fieldErrors.get(0).getDefaultMessage();
log.error(message, e);
}
 HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
HttpHeaders headers = new HttpHeaders();
Response response = new Response();
response.setCode(ResponseEnum.FORMAT_ERROR.code());
response.setMessage(ResponseEnum.FORMAT_ERROR.message());
return new ResponseEntity<>(response, headers, httpStatus);
}

对于使用单个参数接受前端请求,因校验产生的异常类为ConstraintViolationException,示例方法如下:


/**
* 捕获303对于request param单个参数的校验
* @param e
* @param request
* @return
*/@ExceptionHandler(ConstraintViolationException.class)
@ResponseBody
ResponseEntity<Object> handleConstraintViolationException(ConstraintViolationException e, HttpServletRequest request){
 HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
HttpHeaders headers = new HttpHeaders();
Response response = new Response();
response.setCode(ResponseEnum.FORMAT_ERROR.code());
response.setMessage(ResponseEnum.FORMAT_ERROR.message());
return new ResponseEntity<>(response, headers, httpStatus);
}

来源:https://segmentfault.com/a/1190000037601525

标签:SpringBoot,jsr303,校验
0
投稿

猜你喜欢

  • 详解Springboot分布式限流实践

    2021-07-12 14:29:18
  • JDK 7U15在 Windows x86平台下的安装方法

    2023-04-09 07:31:08
  • SpringBoot配置SwaggerUI访问404错误的解决方法

    2021-10-02 19:33:56
  • 用intellij Idea加载eclipse的maven项目全流程(图文)

    2021-09-12 06:11:16
  • 基于Java的guava开源库工具类

    2022-04-07 05:37:53
  • SpringBoot Security安装配置及Thymeleaf整合

    2023-11-27 16:18:41
  • 基于Mybatis映射的一点心得(分享)

    2023-08-08 13:15:53
  • android实现简易计算器

    2023-06-21 04:26:09
  • Maven+Tomcat8 实现自动化部署的方法

    2023-01-03 06:44:20
  • Java构建JDBC应用程序的实例操作

    2023-08-07 12:09:13
  • java底层JDK Logging日志模块处理细节深入分析

    2023-02-04 12:47:31
  • Java聊天室之实现接收和发送Socket

    2021-06-24 23:30:39
  • java面试题——详解HashMap和Hashtable 的区别

    2023-08-06 16:38:25
  • Java编程实现中英混合字符串数组按首字母排序的方法

    2022-03-16 02:34:54
  • C#控制图像旋转和翻转的方法

    2023-11-26 08:25:08
  • java list随机抽取元素的案例

    2023-12-22 22:21:59
  • Java创建类模式_动力节点Java学院整理

    2023-04-15 23:11:55
  • 聊一聊SpringBoot服务监控机制

    2023-02-09 02:47:48
  • Android Studio 多层级 Module 对 aar 引用问题解决方法

    2023-08-06 19:41:27
  • 关于Java8 parallelStream并发安全的深入讲解

    2023-11-15 06:37:35
  • asp之家 软件编程 m.aspxhome.com