SpringBoot参数校验
    		       		warning:
    		            这篇文章距离上次修改已过423天,其中的内容可能已经有所变动。
    		        
        		                
                在Spring Boot中,可以使用@Validated注解和JSR-380(Hibernate Validator)提供的注解来实现参数的校验。首先,需要在pom.xml中添加依赖:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>然后,可以在控制器的方法参数上使用@Validated注解来启用校验,并在相应的字段上使用Hibernate Validator提供的校验注解,如@NotNull、@Size、@Min、@Max等。
以下是一个简单的例子:
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
 
@Validated
@RestController
public class MyController {
 
    @PostMapping("/submit")
    public String submitData(@RequestBody @Valid MyData data) {
        // 处理请求
        return "Data is valid";
    }
 
    static class MyData {
        @NotNull(message = "Name cannot be null")
        private String name;
 
        @Size(min = 10, max = 200, message = "Description must be between 10 and 200 characters")
        private String description;
 
        // Getters and setters
    }
}在这个例子中,MyData 类中的字段 name 和 description 将根据注解进行校验。如果请求体中的数据不符合校验规则,Spring Boot会自动返回400(Bad Request)响应。
评论已关闭