使用 @Validated 和 全局异常进行参数校验

2024-09-03 02:38

本文主要是介绍使用 @Validated 和 全局异常进行参数校验,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

如果你用的 Spring Boot 版本小于 2.3.x,spring-boot-starter-web 会自动引入 hibernate-validator 的依赖。如果 Spring Boot 版本大于 2.3.x,则需要手动引入依赖:

<dependency><groupId>org.hibernate</groupId><artifactId>hibernate-validator</artifactId><version>6.0.1.Final</version>
</dependency>

常用的校验注解:

定义参数验证结果类:

public class RCode{private int code;private String msg;public RCode(int code, String msg) {super();this.code = code;this.msg = msg;}public int getCode() {return code;}public void setCode(int code) {this.code = code;}public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}}

定义全局异常类:

需要确保下面的类能被spring扫描到,否则可能出现校验失效的情况

@RestControllerAdvice
public class GlobalExceptionHandler {@ExceptionHandler(value = ConstraintViolationException.class)public RCode handle1(ConstraintViolationException ex) {StringBuilder msg = new StringBuilder();Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations();for (ConstraintViolation<?> constraintViolation : constraintViolations) {PathImpl pathImpl = (PathImpl) constraintViolation.getPropertyPath();String paramName = pathImpl.getLeafNode().getName();String message = constraintViolation.getMessage();msg.append("[").append(message).append("]");}return new RCode(1, msg.toString());}@ExceptionHandler(value = Exception.class)public RCode handle1(Exception ex) {ex.printStackTrace();return new RCode(404, ex.getMessage());}@ExceptionHandler(ArithmeticException.class)public RCode handle2(Exception ex) {return new RCode(404, "算数异常");}@ExceptionHandler(BindException.class)public RCode exceptionHandler(BindException e, HttpServletRequest request) {String failMsg = e.getBindingResult().getFieldError().getDefaultMessage();return new RCode(404, failMsg);}
}

定义参数验证类:在需要验证的参数上面添加对应的验证注解

public class User {public interface Default {}public interface Group1 {}@NotNull(message = "userId不能为空", groups = { Default.class, Group1.class })private String userId;@NotNull(message = "userName不能为空", groups = Group1.class)private String userName;@Range(min = 18, max = 60, message = "年龄必须在18-60之间", groups = Group1.class)private int age;public String getUserId() {return userId;}public void setUserId(String userId) {this.userId = userId;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}

上面的 group 可以按照不同的group名称对参数进行不同要求的校验

controller类:

@Validated
@RestController
@RequestMapping("/testService")
public class TestController {@ResponseBody@RequestMapping(value = "/test", produces = "application/json;charset=utf-8", method = { RequestMethod.POST, RequestMethod.GET })public String test(@Validated(value = { User.Default.class }) User user) {return "userId " + user.getUserId();}@ResponseBody@RequestMapping(value = "/test2", produces = "application/json;charset=utf-8", method = { RequestMethod.POST, RequestMethod.GET })public String test2(@Validated(value = { User.Group1.class }) User user) {return "userId " + user.getUserId();}@ResponseBody@RequestMapping(value = "/test3", produces = "application/json;charset=utf-8", method = { RequestMethod.POST, RequestMethod.GET })public String test3(@Validated(value = { User.Group1.class }) User user) {System.out.println(1 / 0);return "userId " + user.getUserId();}}

在需要校验的参数前面添加 @Validated 注解即可,针对不同接口需要不同参数,只需要在 @Validated 里面知道group的值即可

测试

test不传参数的时候:

test2只传一个userId的时候:

 

这篇关于使用 @Validated 和 全局异常进行参数校验的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1131794

相关文章

SpringBoot结合Docker进行容器化处理指南

《SpringBoot结合Docker进行容器化处理指南》在当今快速发展的软件工程领域,SpringBoot和Docker已经成为现代Java开发者的必备工具,本文将深入讲解如何将一个SpringBo... 目录前言一、为什么选择 Spring Bootjavascript + docker1. 快速部署与

深入理解Go语言中二维切片的使用

《深入理解Go语言中二维切片的使用》本文深入讲解了Go语言中二维切片的概念与应用,用于表示矩阵、表格等二维数据结构,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧... 目录引言二维切片的基本概念定义创建二维切片二维切片的操作访问元素修改元素遍历二维切片二维切片的动态调整追加行动态

Spring Boot spring-boot-maven-plugin 参数配置详解(最新推荐)

《SpringBootspring-boot-maven-plugin参数配置详解(最新推荐)》文章介绍了SpringBootMaven插件的5个核心目标(repackage、run、start... 目录一 spring-boot-maven-plugin 插件的5个Goals二 应用场景1 重新打包应用

prometheus如何使用pushgateway监控网路丢包

《prometheus如何使用pushgateway监控网路丢包》:本文主要介绍prometheus如何使用pushgateway监控网路丢包问题,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录监控网路丢包脚本数据图表总结监控网路丢包脚本[root@gtcq-gt-monitor-prome

Python通用唯一标识符模块uuid使用案例详解

《Python通用唯一标识符模块uuid使用案例详解》Pythonuuid模块用于生成128位全局唯一标识符,支持UUID1-5版本,适用于分布式系统、数据库主键等场景,需注意隐私、碰撞概率及存储优... 目录简介核心功能1. UUID版本2. UUID属性3. 命名空间使用场景1. 生成唯一标识符2. 数

linux解压缩 xxx.jar文件进行内部操作过程

《linux解压缩xxx.jar文件进行内部操作过程》:本文主要介绍linux解压缩xxx.jar文件进行内部操作,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、解压文件二、压缩文件总结一、解压文件1、把 xxx.jar 文件放在服务器上,并进入当前目录#

SpringBoot中如何使用Assert进行断言校验

《SpringBoot中如何使用Assert进行断言校验》Java提供了内置的assert机制,而Spring框架也提供了更强大的Assert工具类来帮助开发者进行参数校验和状态检查,下... 目录前言一、Java 原生assert简介1.1 使用方式1.2 示例代码1.3 优缺点分析二、Spring Fr

Android kotlin中 Channel 和 Flow 的区别和选择使用场景分析

《Androidkotlin中Channel和Flow的区别和选择使用场景分析》Kotlin协程中,Flow是冷数据流,按需触发,适合响应式数据处理;Channel是热数据流,持续发送,支持... 目录一、基本概念界定FlowChannel二、核心特性对比数据生产触发条件生产与消费的关系背压处理机制生命周期

java使用protobuf-maven-plugin的插件编译proto文件详解

《java使用protobuf-maven-plugin的插件编译proto文件详解》:本文主要介绍java使用protobuf-maven-plugin的插件编译proto文件,具有很好的参考价... 目录protobuf文件作为数据传输和存储的协议主要介绍在Java使用maven编译proto文件的插件

SpringBoot线程池配置使用示例详解

《SpringBoot线程池配置使用示例详解》SpringBoot集成@Async注解,支持线程池参数配置(核心数、队列容量、拒绝策略等)及生命周期管理,结合监控与任务装饰器,提升异步处理效率与系统... 目录一、核心特性二、添加依赖三、参数详解四、配置线程池五、应用实践代码说明拒绝策略(Rejected