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异常,可以自定义异常处理器进行捕获处理。
  • 其他的需要自行探索

打完收工!

相关推荐
考虑考虑1 小时前
@FilterRegistration和@ServletRegistration注解
spring boot·后端·spring
一只叫煤球的猫1 小时前
🔥 同事混用@Transactional和TransactionTemplate被我怼了,三种事务管理到底怎么选?
java·spring boot·后端
华子w9089258599 天前
基于 SpringBoot+JSP 的医疗预约与诊断系统设计与实现
java·spring boot·后端
java—大象9 天前
基于java SSM的房屋租赁系统设计和实现
java·开发语言·数据库·spring boot·layui·mybatis
Mutig_s9 天前
Spring Boot动态数据源切换:优雅实现多数据源管理
java·数据库·spring boot·后端·mybatis
weixin_425023009 天前
Spring Boot使用MCP服务器
服务器·spring boot·后端·spring ai·mcp
weixin_438335409 天前
Spring Boot:运用Redis统计用户在线数量
java·spring boot·redis
超级小忍9 天前
Spring Boot 集成 Apache Kafka 实战指南
spring boot·kafka·apache
程序员小刚10 天前
基于SpringBoot + Vue 的网上拍卖系统
vue.js·spring boot·后端