一: 一般校验
(0)适用场景:同一字段没有互相矛盾的验证策略
(1) 请求参数
public class ParamsValidForm { @NotBlank(message = "用户名不能为空") private String userName; @NotBlank(message = "密码不能为空") @Length(min = 6, message = "密码长度至少6位") private String password; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { final StringBuffer sb = new StringBuffer("ParamsValidForm{"); sb.append("userName='").append(userName).append('\''); sb.append(", password='").append(password).append('\''); sb.append('}'); return sb.toString(); } }
(2)controller层
/** * 1. 一般校验 * 场景:同一字段没有互相矛盾的验证策略 */ @PostMapping(value = "valid") public ServerResponse valid(@RequestBody @Valid ParamsValidForm paramsValidForm, BindingResult results) { if (results.hasErrors()) { return ServerResponse.createByErrorMessage(results.getFieldError().getDefaultMessage()); } return ServerResponse.createBySuccess(); }
二: 分组校验
(0)适用场景:相同字段在不同场景需要不同的验证策略
(1)请求参数
public class GroupsValidForm { @Null(message = "id必须为null", groups = {GroupVaildDTO.SaveGroup.class}) @NotNull(message = "id不能为null", groups = {GroupVaildDTO.UpdateGroup.class}) private Integer id; @NotBlank(message = "用户名不能为空") private String userName; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } @Override public String toString() { final StringBuffer sb = new StringBuffer("GroupsValidForm{"); sb.append("id=").append(id); sb.append(", userName='").append(userName).append('\''); sb.append('}'); return sb.toString(); } }
(2)组接口
public class GroupVaildDTO { public interface SaveGroup extends Default {} public interface UpdateGroup extends Default {} }
(3)controller层
/** * 2. 分组校验 * 场景:相同字段在不同场景需要不同的验证策略 */ @PostMapping(value = "update") public ServerResponse update(@RequestBody @Validated(value = GroupVaildDTO.UpdateGroup.class) GroupsValidForm groupsValidForm, BindingResult results) { if (results.hasErrors()) { return ServerResponse.createByErrorMessage(results.getFieldError().getDefaultMessage()); } return ServerResponse.createBySuccess(); }