ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的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 ```