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
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
详解Springboot分布式限流实践
![](https://img.aspxhome.com/file/2023/7/64217_0s.png)
JDK 7U15在 Windows x86平台下的安装方法
![](https://img.aspxhome.com/file/2023/4/72324_0s.png)
SpringBoot配置SwaggerUI访问404错误的解决方法
![](https://img.aspxhome.com/file/2023/3/68743_0s.png)
用intellij Idea加载eclipse的maven项目全流程(图文)
![](https://img.aspxhome.com/file/2023/2/60082_0s.jpg)
基于Java的guava开源库工具类
SpringBoot Security安装配置及Thymeleaf整合
基于Mybatis映射的一点心得(分享)
android实现简易计算器
![](https://img.aspxhome.com/file/2023/4/83514_0s.jpg)
Maven+Tomcat8 实现自动化部署的方法
Java构建JDBC应用程序的实例操作
java底层JDK Logging日志模块处理细节深入分析
Java聊天室之实现接收和发送Socket
![](https://img.aspxhome.com/file/2023/8/69118_0s.png)
java面试题——详解HashMap和Hashtable 的区别
Java编程实现中英混合字符串数组按首字母排序的方法
C#控制图像旋转和翻转的方法
java list随机抽取元素的案例
![](https://img.aspxhome.com/file/2023/0/71920_0s.jpg)
Java创建类模式_动力节点Java学院整理
聊一聊SpringBoot服务监控机制
![](https://img.aspxhome.com/file/2023/9/64169_0s.png)
Android Studio 多层级 Module 对 aar 引用问题解决方法
![](https://img.aspxhome.com/file/2023/2/86762_0s.png)
关于Java8 parallelStream并发安全的深入讲解
![](https://img.aspxhome.com/file/2023/5/59545_0s.png)