这篇文篇主要简述如何在springboot中验证表单信息。在springmvc工程中,需要检查表单信息,表单信息验证主要通过注解的形式。
构建工程
创建一个springboot工程,由于用到了 web 、thymeleaf、validator、el,引入相应的起步依赖和依赖,代码清单如下:
![9699640a83212abee7bf2d6eabed2440.png](https://i-blog.csdnimg.cn/blog_migrate/42c637298c371892816e2b778117548b.jpeg)
创建一个PresonForm的Object类
![647a18c3244526b600ba176578e46bc0.png](https://i-blog.csdnimg.cn/blog_migrate/ac624ede5f1fd2a475d13dc809c19427.jpeg)
这个实体类,在2个属性:name,age.它们各自有验证的注解:
- @Size(min=2, max=30) name的长度为2-30个字符
- @NotNull 不为空
- @Min(18)age不能小于18
创建 web Controller
![e4e1f5f935ab66aaf9cc595172dda5b8.png](https://i-blog.csdnimg.cn/blog_migrate/ce09e5f1b926be561b5f38e92c007c3e.jpeg)
创建form表单
src/main/resources/templates/form.html:
![4f3853b0420e80f499916f424bd07e34.png](https://i-blog.csdnimg.cn/blog_migrate/62d79e31ca61a82c8d1a60e1085ebdeb.jpeg)
注册成功的页面
src/main/resources/templates/results.html:
html> Congratulations! You are old enough to sign up for this site.