5.SpringBoot之服务端表单数据校验

1.SpringBoot 对表单做数据校验

1.1SpringBoot 对表单数据校验的技术特点

SpringBoot 中使用了 Hibernate-validate 校验框架

1.2SpringBoot 表单数据校验步骤

1.2.1在实体类中添加校验规则

public class Users {
@NotBlank //非空校验
private String name;
@NotBlank //密码非空校验
private String password;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Users [name=" + name + ", password=" + password + ", age="
+ age + "]";
}
}

1.2.2在 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";
}

1.2.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>

2.其他校验规则

@NotBlank: 判断字符串是否为 null 或者是空串(去掉首尾空格)。
@NotEmpty: 判断字符串是否 null 或者是空串。
@Length: 判断字符的长度(最大或者最小)
@Min: 判断数值最小值
@Max: 判断数值最大值
@Email: 判断邮箱是否合法

猜你喜欢

转载自blog.csdn.net/qq_43051879/article/details/86502804