使用 @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

相关文章

使用Java将各种数据写入Excel表格的操作示例

《使用Java将各种数据写入Excel表格的操作示例》在数据处理与管理领域,Excel凭借其强大的功能和广泛的应用,成为了数据存储与展示的重要工具,在Java开发过程中,常常需要将不同类型的数据,本文... 目录前言安装免费Java库1. 写入文本、或数值到 Excel单元格2. 写入数组到 Excel表格

redis中使用lua脚本的原理与基本使用详解

《redis中使用lua脚本的原理与基本使用详解》在Redis中使用Lua脚本可以实现原子性操作、减少网络开销以及提高执行效率,下面小编就来和大家详细介绍一下在redis中使用lua脚本的原理... 目录Redis 执行 Lua 脚本的原理基本使用方法使用EVAL命令执行 Lua 脚本使用EVALSHA命令

Java 中的 @SneakyThrows 注解使用方法(简化异常处理的利与弊)

《Java中的@SneakyThrows注解使用方法(简化异常处理的利与弊)》为了简化异常处理,Lombok提供了一个强大的注解@SneakyThrows,本文将详细介绍@SneakyThro... 目录1. @SneakyThrows 简介 1.1 什么是 Lombok?2. @SneakyThrows

在 Spring Boot 中实现异常处理最佳实践

《在SpringBoot中实现异常处理最佳实践》本文介绍如何在SpringBoot中实现异常处理,涵盖核心概念、实现方法、与先前查询的集成、性能分析、常见问题和最佳实践,感兴趣的朋友一起看看吧... 目录一、Spring Boot 异常处理的背景与核心概念1.1 为什么需要异常处理?1.2 Spring B

SpringBoot3.4配置校验新特性的用法详解

《SpringBoot3.4配置校验新特性的用法详解》SpringBoot3.4对配置校验支持进行了全面升级,这篇文章为大家详细介绍了一下它们的具体使用,文中的示例代码讲解详细,感兴趣的小伙伴可以参考... 目录基本用法示例定义配置类配置 application.yml注入使用嵌套对象与集合元素深度校验开发

使用Python和Pyecharts创建交互式地图

《使用Python和Pyecharts创建交互式地图》在数据可视化领域,创建交互式地图是一种强大的方式,可以使受众能够以引人入胜且信息丰富的方式探索地理数据,下面我们看看如何使用Python和Pyec... 目录简介Pyecharts 简介创建上海地图代码说明运行结果总结简介在数据可视化领域,创建交互式地

Java Stream流使用案例深入详解

《JavaStream流使用案例深入详解》:本文主要介绍JavaStream流使用案例详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录前言1. Lambda1.1 语法1.2 没参数只有一条语句或者多条语句1.3 一个参数只有一条语句或者多

利用python实现对excel文件进行加密

《利用python实现对excel文件进行加密》由于文件内容的私密性,需要对Excel文件进行加密,保护文件以免给第三方看到,本文将以Python语言为例,和大家讲讲如何对Excel文件进行加密,感兴... 目录前言方法一:使用pywin32库(仅限Windows)方法二:使用msoffcrypto-too

Java Spring 中 @PostConstruct 注解使用原理及常见场景

《JavaSpring中@PostConstruct注解使用原理及常见场景》在JavaSpring中,@PostConstruct注解是一个非常实用的功能,它允许开发者在Spring容器完全初... 目录一、@PostConstruct 注解概述二、@PostConstruct 注解的基本使用2.1 基本代

C#使用StackExchange.Redis实现分布式锁的两种方式介绍

《C#使用StackExchange.Redis实现分布式锁的两种方式介绍》分布式锁在集群的架构中发挥着重要的作用,:本文主要介绍C#使用StackExchange.Redis实现分布式锁的... 目录自定义分布式锁获取锁释放锁自动续期StackExchange.Redis分布式锁获取锁释放锁自动续期分布式