Spring Boot 使用validation校验参数

Spring Boot 使用validation校验参数

项目场景:

在看公司代码的时候,发现是用了Spring Boot Validation去检验参数的,但是后面又在代码里去检验参数去了,而且这个Spring Boot Validation校验好像并不生效。于是自己摸索研究了一下。


引入依赖

虽然项目使用的校验都是javax.validation,但是不引入这个依赖他是真的不生效。

gradle如下:

java 复制代码
implementation 'org.springframework.boot:spring-boot-starter-validation'

使用

如上,只需要使用注解即可,不要怀疑,他就是javax.validation包里的

校验代码

代码如下:

java 复制代码
	@PostMapping("/test")
    public ResponseEntity<String> test(@RequestBody @Valid Request request){
        return ResponseEntity.ok("OK");
    }

实体类

java 复制代码
@Data
public class PudaoCreditRequest {

    @NotNull(message = "id must be not empty")
    private Integer id;

    @NotNull(message = "id2must be not empty")
    private Integer id2;

    @Size(min = 1, max = 20)
    @Pattern(regexp = "^[a-zA-Z0-9_ ]*$", message = "pattern is not proper for channel data ")
    private String test1;
}

说明

  • @NotNull就是判断不是Null
  • @NotEmpty判断非空字符串
  • @Size判断长度
  • @Pattern 可以自定义校验,但是不能用于Integer
  • @Valid开启校验
  • 该校验会抛出org.springframework.web.bind.MethodArgumentNotValidException异常,可以自定义异常处理器进行捕获处理。
  • 其他的需要自行探索

打完收工!

相关推荐
riNt PTIP16 小时前
SpringBoot创建动态定时任务的几种方式
java·spring boot·spring
星晨羽18 小时前
西门子机床opc ua协议实现变量读写及NC文件上传下载
java·spring boot
yuweiade18 小时前
Spring Boot 整合 Redis 步骤详解
spring boot·redis·bootstrap
三水不滴19 小时前
SpringAI + SpringDoc + Knife4j 构建企业级智能问卷系统
经验分享·spring boot·笔记·后端·spring
2601_9498146919 小时前
Docker部署Spring Boot + Vue项目
vue.js·spring boot·docker
RDCJM1 天前
Springboot的jak安装与配置教程
java·spring boot·后端
志飞1 天前
springboot配置可持久化本地缓存ehcache
java·spring boot·缓存·ehcache·ehcache持久化
weixin_704266051 天前
Spring Cloud Gateway
spring boot
lclcooky1 天前
Spring Boot 整合 Keycloak
java·spring boot·后端
William Dawson1 天前
【一文吃透 Spring Boot 面向切面编程(AOP):实例\+实现\+注意事项】
java·spring boot