SpringBoot之表单验证@Valid

SpringBoot提供了强大的表单验证功能实现,给我们省去了写验证的麻烦;

这里我们给下实例,提交一个有姓名和年龄的表单添加功能,

要求姓名不能为空,年龄必须是不小于18 ;

我们先新建一个Student实体
SpringBoot之表单验证@Valid
SpringBoot之表单验证@Valid
SpringBoot之表单验证@Valid
dao接口写下:
SpringBoot之表单验证@Valid
service接口写下:
SpringBoot之表单验证@Valid
service接口实现类写下:
SpringBoot之表单验证@Valid
controller写下:
SpringBoot之表单验证@Valid
add方法里 实体前要加@Valid 假如字段验证不通过,信息绑定到后面定义的BindingResult; 所以首先if判断bindingResult对象里是否有错误信息,如果没有那就说明字段验证通过,直接执行else里面的studentService.add()方法

student添加页面studentAdd.html
SpringBoot之表单验证@Valid
浏览器请求:http://localhost:8888/studentAdd.html
SpringBoot之表单验证@Valid
直接点击提交
SpringBoot之表单验证@Valid
输入姓名后,提交
SpringBoot之表单验证@Valid
输入年龄5,提交
SpringBoot之表单验证@Valid
我们改成20,提交
SpringBoot之表单验证@Valid
提交通过。