一、业务场景
对于一个用户的注册操作(Post请求),往往涉及到账号(username)、密码(password)的Post提交:
//用户发送POST请求创建新的用户
@PostMapping
public User create(@RequestBody User user){
/**
一些数据持久化操作,如:写入数据库
**/
//打印用户提交的信息
System.out.println(user.getId());
System.out.println(user.getUsername());
System.out.println(user.getPassword());
System.out.println(user.getBirthday());
return user;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
二、业务出现的问题
但用户往往会不小心提交了空的密码来注册,这是不允许的,因此我们往往需要对用户提交的密码信息进行空判断,常见的方法是直接进行if语句的空判断:
//用户发送POST请求创建新的用户
@PostMapping
public User create(@RequestBody User user){
if( StringUtils.isBlank(user.getPassword())){
//用户输入密码为空,进行异常处理
}
/**
一些数据持久化操作,如:写入数据库
**/
//打印用户提交的信息
System.out.println(user.getId());
System.out.println(user.getUsername());
System.out.println(user.getPassword());
System.out.println(user.getBirthday());
return user;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
以上方法看似行得通,但一旦Post的方法变多,则需要对每个Post请求都进行一次if判断是否为空,代码变得冗余,而且一旦修改一个地方,所有if语句都需要修改,可维护性就变得很差。
三、优化的解决方案
那么,有没有一种方法可以一劳永逸、既没有大量代码冗余,可维护性又好呢?这时 javax.validation包下的@Valid注解就派上用场了。
1.首先,我们在实体类User.java中的密码(password)属性加上@NotBlank注解(hibernate.validator.constraints包)
import org.hibernate.validator.constraints.NotBlank;
public class User {
public interface UserSimpleView{}
public interface UserDetailView extends UserSimpleView{}
private String username;
//给该属性加入NotBlank非空的约束
@NotBlank
private String password;
private String id;
private Date birthday;
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@JsonView(UserSimpleView.class)
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@JsonView(UserSimpleView.class)
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@JsonView(UserDetailView.class)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
2.我们在Controller类的Post方法的参数中加入@Valid注解,并使用BindingResult将错误信息作为日志打印到后台
@PostMapping
public User create(@Valid @RequestBody User user,
BindingResult errors){
if (errors.hasErrors()){
//异常处理
errors.getAllErrors().stream().forEach(error -> System.out.println(error.getDefaultMessage()));
}
user.setId("1");
System.out.println(user.getId());
System.out.println(user.getUsername());
System.out.println(user.getPassword());
System.out.println(user.getBirthday());
return user;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
3.这时,当我们向服务器Post提交空的密码信息时,后台会打印出错误信息:
may not be empty
- 1