企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
SpringBoot 整合了 Hibernate Validator 框架,使用很方便。 **1. 引入`spring-boot-starter-validation`** ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> ``` **2. 在 controller 标记校验注解/约束注解** ```java /** * 1. 标记校验注解 @Validated */ @Validated @RestController public class PersonController { /** * 2. 标记约束注解 @NotBlank */ @GetMapping("/v1/person/getByName") public String getByName(@RequestParam("name") @NotBlank(message = "name不能为空") String name) { return "[getByName]." + name; } } ``` **3. 测试结果** 如果不携带参数`name`访问:http://localhost:8080/v1/person/getByName?name= ,后台报错,校验不通过。 ```java jakarta.validation.ConstraintViolationException: getByName.name: name不能为空 at org.springframework.validation.beanvalidation.MethodValidationInterceptor.invoke ```