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判斷郵箱是否合法