依赖
1 2 3 4
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
|
@RequestParam
Controller 类上添加 @Validate 注解。
1 2 3 4
| @GetMapping("/param_notnull") public String notnull(@RequestParam("username") @NotEmpty String username) { return username; }
|
@RequestBody
Java Bean 中添加校验,配合方法中的 @Validated 注解。
1 2 3 4
| @PostMapping("/pojo_notnull") public UserReq notnull(@RequestBody @Validated UserReq req) { return req; }
|
1 2 3 4 5 6 7 8 9 10
| @Data public class UserReq {
@NotNull @NotEmpty private String username; }
|
分组校验
group
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
public interface EmailGroup { }
public interface LoginGroup { }
|
controller
1 2 3 4 5 6 7 8 9
| @PostMapping("/pojo_email") public UserReq email(@RequestBody @Validated(value = {EmailGroup.class}) UserReq req) { return req; }
@PostMapping("/pojo_login") public UserReq login(@RequestBody @Validated(value = {LoginGroup.class}) UserReq req) { return req; }
|
POJO
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| @Data public class UserReq {
@NotNull(groups = {LoginGroup.class}) @NotEmpty(groups = {LoginGroup.class}) private String username;
@NotNull(groups = {LoginGroup.class}) @NotEmpty(groups = {LoginGroup.class}) private String password;
@Email(groups = {EmailGroup.class}) @NotEmpty(groups = {EmailGroup.class}) private String email; }
|
代码
here