一、SpringBoot对表单校验的技术特点
1.1 SpringBoot 中使用了 Hibernate-validate 校验框架。
1.2 SpringBoot表单数据校验步骤
1.2.1 在实体类中添加数据校验规则
public class Users {
@NotBlank //非空校验
private String name;
@NotBlank //密码非空校验
private String password;
private Integer age;
1.2.2 在Controler中开启校验方式一:
编写页面跳转Controller
/**
* 在跳转页面的方法中注入一个 Uesrs 对象。
* 注意:由于 springmvc 会将该对象放入到 Model 中传递。key 的名称会使用
* 该对象的驼峰式的命名规则来作为 key。
* 参数的变量名需要与对象的名称相同。将首字母小写。
*
* @param users
* @return
*/
@RequestMapping("/addUser")
public String showPage( Users users){
return "add";
}
编写完成添加操作Controller
/**
* 完成用户添加
*@Valid 开启对 Users 对象的数据校验
*BindingResult:封装了校验的结果
*/
@RequestMapping("/save")
public String saveUser( @Valid Users users,BindingResult result){
if(result.hasErrors()){
return "add";
}
System.out.println(users);
return "ok";
}
编写表单页面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>添加用户</title>
</head>
<body>
<form th:action="@{/save}" method="post">
用户姓名:<input type="text" name="name"/><font color="red" th:errors="${users.name}"></font><br/>
用户密码:<input type="password" name="password" /><font color="red" th:errors="${users.password}"></font><br/>
用户年龄:<input type="text" name="age" /><font color="red" th:errors="${users.age}"></font><br/>
<input type="submit" value="OK"/>
</form>
</body>
</html>
1.2.3 在Controler中开启校验方式二:
编写页面跳转Controller
/**
*
* 如果想为传递的对象更改名称,可以使用@ModelAttribute("aa")这表示当前传递的对象的 key 为 aa。
* 那么我们在页面中获取该对象的 key 也需要修改为 aa
* @param users
* @return
*/
@RequestMapping("/addUser")
public String showPage(@ModelAttribute("aa") Users users){
return "add";
}
编写完成添加操作Controller
/**
* 完成用户添加
*@Valid 开启对 Users 对象的数据校验
*BindingResult:封装了校验的结果
*/
@RequestMapping("/save")
public String saveUser(@ModelAttribute("aa") @Valid Usersusers,BindingResult result){
if(result.hasErrors()){
return "add";
}
System.out.println(users);
return "ok";
}
编写表单页面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>添加用户</title>
</head>
<body>
<form th:action="@{/save}" method="post">
用户姓名:<input type="text" name="name"/><font color="red" th:errors="${aa.name}"></font><br/>
用户密码:<input type="password" name="password" /><font color="red" th:errors="${aa.password}"></font><br/>
用户年龄:<input type="text" name="age" /><font color="red" th:errors="${aa.age}"></font><br/>
<input type="submit" value="OK"/>
</form>
</body>
</html>
1.3 其他校验规则
@NotBlank: 判断字符串是否为 null 或者是空串(去掉首尾空格)。
@NotEmpty: 判断字符串是否 null 或者是空串。
@Length: 判断字符的长度(最大或者最小)
@Min: 判断数值最小值
@Max: 判断数值最大值
@Email: 判断邮箱是否合法