一、验证用到的注解
@Valid | 对传到后台的参数的验证 |
@BindingResult | 配合@Valid使用,验证失败后的返回 |
二、示例
1.传统方式
@PostMapping public User create(@RequestBody User user){ if(StringUtils.isBlank(user.getPassword())){ } //代码省略... return user; }
2.采用新注解的方式
1)默认的校验
package com.knyel.dto; import com.fasterxml.jackson.annotation.JsonView; import org.hibernate.validator.constraints.NotBlank; import java.util.Date; public class User { public interface UserSimpleView {}; public interface UserDetailView extends UserSimpleView {}; private String id; private String username; @NotBlank private String password; private Date birthday; @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; } @JsonView(UserSimpleView.class) public String getId (){ return id; } @JsonView(UserSimpleView.class) public void setId (String id){ this.id = id; } public Date getBirthday (){ return birthday; } public void setBirthday (Date birthday){ this.birthday = birthday; } @Override public String toString (){ return "User{" + "id='" + id + '\'' + ", username='" + username + '\'' + ", password='" + password + '\'' + ", birthday=" + birthday + '}'; } }
@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"); return user; }
输出结果为
may not be empty
也就是应该不能为空
2)自定义校验的错误消息
package com.knyel.dto; import com.fasterxml.jackson.annotation.JsonView; import org.hibernate.validator.constraints.NotBlank; import javax.validation.constraints.Past; import java.util.Date; public class User { public interface UserSimpleView {}; public interface UserDetailView extends UserSimpleView {}; private String id; private String username; @NotBlank(message="密码不能为空") private String password; @Past(message = "生日必须是过去的时间") private Date birthday; @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; } @JsonView(UserSimpleView.class) public String getId (){ return id; } @JsonView(UserSimpleView.class) public void setId (String id){ this.id = id; } public Date getBirthday (){ return birthday; } public void setBirthday (Date birthday){ this.birthday = birthday; } @Override public String toString (){ return "User{" + "id='" + id + '\'' + ", username='" + username + '\'' + ", password='" + password + '\'' + ", birthday=" + birthday + '}'; } }