本帖最后由 小江哥 于 2019-4-19 12:52 编辑
Spring分组校验其实就是增加了一个group来对校验规则进行分组,然后再@Validated中指定group来校验。
代码如下
[Java] 纯文本查看 复制代码 public class User {
@NotNull(groups = {First.class})
private int id;
@NotNull(groups = {First.class, Second.class})
private String username;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
interface First {
}
interface Second {
}
[Java] 纯文本查看 复制代码 @RestController
public class UserControllerTest {
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(@Validated({Second.class}) User user, BindingResult result) {
if (result.hasErrors()) {
return "validate/error";
}
return "redirect:/success";
}
@RequestMapping(value = "/update", method = RequestMethod.PUT)
public String update(@Validated({First.class, Second.class}) User user, BindingResult result) {
if (result.hasErrors()) {
return "validate/error";
}
return "redirect:/success";
}
}
|