解析Java中的数据校验:从Bean Validation到Spring Boot集成
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import javax.validation.constraints.Min;
import javax.validation.constraints.Max;
import javax.validation.constraints.Email;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@RestController
class UserController {
@PostMapping("/users")
String createUser(@Validated @RequestBody User user) {
// 逻辑处理
return "User created: " + user.toString();
}
}
@Validated
class User {
@NotBlank(message = "The name of the user must not be blank")
@Size(min = 2, max = 30)
private String name;
@Min(value = 18, message = "User must be at least 18 years old")
@Max(value = 120, message = "User must not be older than 120 years")
private int age;
@Email(message = "Must be a valid email address")
private String email;
// Getters and Setters
}
这个代码示例展示了如何在Spring Boot应用程序中使用Bean Validation注解来验证传入的用户数据。@Validated
注解被用于开启方法参数上的验证,而@NotBlank
、@Size
、@Min
、@Max
和@Email
注解则分别用于确保字段值不为空、字符串长度在指定范围内、整数值在指定范围内以及字段值是一个有效的电子邮件地址。如果验证失败,Spring Boot会返回一个错误信息。
评论已关闭