springmvc中@valid的分组校验
@valid分组校验及顺序
⾸先任意定义两个接⼝:
接着使⽤@GroupSequence({First.class,Second.class,Student.class})(Student为实体类,意思为:除了定义的按分组顺序外,其他按照Student实体类中的顺序执⾏),会按照 First.class、Second.class的顺序进⾏校验,最后按指定实体类Student那些没分组的继续校验:
@GroupSequence({First.class,Second.class,Student.class})
public class Student implements Serializable {
private Long id;
@NotBlank(groups = {First.class})
@Length(min = 3,max = 15,groups = {Second.class})
private String name;
在@Controler 配置如下:
@PostMapping(path = "/create")
public String create(@Valid @ModelAttribute Student student,
BindingResult bindingResult,
RedirectAttributes redirectAttributes){
//执⾏处理器⽅法之前,⾸先要进⾏数据校验,会有⼀个结果 bindingResult
if(bindingResult.hasErrors()){ //如果有错误,则应该返回到表单视图
//因为表单需要与student对象绑定,所以它必须要放到Model中
return "/student/create";
}
studentService.saveOrUpdate(student);
//提⽰信息
redirectAttributes.addFlashAttribute("message","添加成功");
return "redirect:/students";