步骤1 - bean类的属性上添加校验规则注解
伪代码
public class Human {
@NotEmpty(message="{human.name.notEmpty}")
String name;
}
步骤2 - Resource 下新建错误信息配置文件ValidationMessages.properties
ValidationMessages.properties
#格式:类名.属性名.注解名=信息
human.name.notEmpty=your name is not empty
步骤3 - Controller方法形参上开启校验 - 添加@Validated注解
// 形参上添加注解、Errors接收校验产生的异常、model填充渲染的数据
@PostMapping("add")
public String add(@Validated Human human, Errors errors, Model model) {
model.addAttribute("errors", errors);
if(errors.hasErrors()) {
List<FieldError> fieldErrors = errors.getFieldErrors();
for(FieldError error : fieldErrors) {
// 获取校验不通过后ValidationMessages对应的属性段信息
System.out.println(error.getField() + "==========" + error.getDefaultMessage());
}
return "/date/addDate";
}
humans.add(human);
return "redirect:/dates";
}