SpringMVC 参数校验

依赖

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 {
/**
* 用户名<br>
* username != null
*/
@NotNull
@NotEmpty
private String username;
}

分组校验

group

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* Usage: {@link ValidationController#email(UserReq)} <br/>
* Date: 2023/5/24 16:14 <br/>
*
* @author <a href="mailto:hanzhang2566@foxmail.com">hanzhang</a>
*/
public interface EmailGroup {
}

/**
* Usage: {@link ValidationController#login(UserReq)} <br/>
* Date: 2023/5/24 16:18 <br/>
*
* @author <a href="mailto:hanzhang2566@foxmail.com">hanzhang</a>
*/
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