springboot校验数据
1.实体类
public class Users {
@NotBlank //非空校验
private String name;
@NotBlank //密码非空校验
private String password;
private Integer age;
- Controller 中开启校验
- 完成用户添加
- *@Valid 开启对 Users 对象的数据校验
- *BindingResult:封装了校验的结果 */
**注意:**必须在跳转页面的方法中注入一个 Uesrs 对象,:由于 springmvc 会将该对象放入到 Model 中传递。key 的名称会使用 该对象的驼峰式的命名规则来作为 key,参数的变量名需要与对象的名称相同。将首字母小写
@RequestMapping("/addUser")
public String showPage( Users users)
{ return "add"; }
@RequestMapping("/save")
public String saveUser(@Valid Users users,BindingResult result){
return "ok";
}
3.页面中获取提示信息
<!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>