Springboot中使用了Hibernate-validate作为默认表单数据校验框架
在实体类上的具体字段添加注解
1 public class User { 2 @NotBlank 3 private String name; 4 @NotBlank 5 private String password; 6 private Integer age; 7 //set、get方法......
8 }
在controller中开启校验
1 @RequestMapper("/save") 2 public String saveUser(@Valid User user, BindingResult bindingResult) { 3 if(bindingResult.hasErrors()) { 4 //返回原来页面,模板引擎能拿到bindingResult中的error
5 return "add"; 6 } else { 7 return "ok"; 8 } 9 }
thymeleaf页面
1 <html>
2 <head>
3 <meta charset="utf-8">
4 </head>
5 <body>
6 <form th:action="@{/save}" method="post">
7 用户姓名:<input type="text" name="name"/>
8 <font color="red" th:errors="${user.name}"></font><br/>
9 用户密码:<input type="password" name="password" />
10 <font color="red" th:errors="${user.password}"></font><br/>
11 用户年龄:<input type="text" name="age" />
12 <font color="red" th:errors="$user.age"></font><br/>
13 <input type="submit" value="ok">
14 </form>
15 </body>
16 </html>
首次打开此模板页面可能报错,因为需要user对象,于是在controller中这样写
1 @RequestMapping("addUser") 2 public String showPage(@ModelAttribute("user") User user) { 3 return "add"; 4 } 5
6 @RequestMapping("save") 7 public String saveUser(@ModelAttribute("user") @Valid User user, BindingResult bindingResult) { 8 if(bindingResult.hasErrors()) { 9 return "add"; 10 } else { 11 return "ok"; 12 } 13 }
Hibernate-Validate常用校验规则
@NotBlank:判断字符创是否是null或者是空串(去掉首尾空格)。
@NotEmpty判断字符串是否为null会者是空串。
@Length判断字符的长度(最大或最小)
@Min判断数值最小值
@Max判断数值最大值
@Email判断邮箱是否合法