构建微服务 :Spring boot数据校验
SpringBoot提供了强大的表单验证功能实现,给我们省去了写验证的麻烦。 SpringBoot对表单数据校验的技术特点:
SpringBoot中使用了Hibernate-validate校验框架。
数据校验
实现添加用户功能
- 创建项目
修改POM文件
导入Springboot和thymeleaf的启动器。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.xianglei</groupId>
<artifactId>SpringBootCheck</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent>
<properties>
<thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.0.4</thymeleaf-layout-dialect.version>
</properties>
<dependencies>
<!-- springBoot的启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- thymeleaf的启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
</project>
编写添加用户功能
- 创建实体类
package com.xianglei.pojo;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotBlank;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
public class Users {
@NotBlank(message = "名字不能为空哦!") //非空校验
private String name;
@NotBlank //密码非空校验
@Length(max = 15,min = 8)
private String password;
@Max(99)
@Min(1)
private Integer age;
@Email
private String email;
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;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
- 编写Controller
@Controller
public class UserController {
@RequestMapping("/showpage")
public String showpage(@ModelAttribute("users") Users users){
return "add";
}
@RequestMapping("/login")
public String saveUser(@ModelAttribute("users") @Valid Users users, BindingResult result){
if(result.hasErrors()){
return "add";
}
System.out.println(users);
return "ok";
}
}
- 编写页面 add.html ok.html
<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form th:action="@{/login}" method="post">
用户姓名:<label>
<input type="text" name="name"/>
</label><span th:errors="${users.name}" style="color: red; "></span><br/>
用户密码:<label>
<input type="password" name="password"/>
</label><span th:errors="${users.password}" style="color: red; "></span><br/>
用户年龄:<label>
<input type="text" name="age"/>
</label><span th:errors="${users.age}" style="color: red; "></span><br/>
邮箱:<label>
<input type="text" name="email"/>
</label><span th:errors="${users.email}" style="color: red; "></span><br/>
<input type="submit" value="OK"/>
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
OK
</body>
</html>
SpringBoot对表单做数据校验
在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>
如果遇到异常
- 解决数据校验时的异常问题
解决异常的方法,在跳转页面的方法中注入一个对象,来解决问题。要求参数对象的变量名必须是对象的类名的全称首字母小写。
代码
/**
* 解决异常的方式。可以在跳转页面的方法中注入一个Uesrs对象。
* 注意:由于springmvc会将该对象放入到Model中传递。key的名称会使用该对象的驼峰式的命名规则来作为key。
* 参数的变量名需要与对象的名称相同。将首字母小写。
*
* @param users
* @return
*/
@RequestMapping("/addUser")
public String showPage( Users users){
return "add";
}
/**
* 完成用户添加
*@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>
如果你的参数的名称需要做改变,那么对应的网页中的也做出相应改变。
/**
*
* 如果想为传递的对象更改名称,可以使用@ModelAttribute("aa")这表示当前传递的对象的key为aa。
* 那么我们在页面中获取该对象的key也需要修改为aa
* @param users
* @return
*/
@RequestMapping("/addUser")
public String showPage(@ModelAttribute("aa") Users users){
return "add";
}
/**
* 完成用户添加
*@Valid 开启对Users对象的数据校验
*BindingResult:封装了校验的结果
*/
@RequestMapping("/save")
public String saveUser(@ModelAttribute("aa") @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="${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>
其他校验规则
- @NotBlank: 判断字符串是否为null或者是空串(去掉首尾空格)。
- @NotEmpty: 判断字符串是否null或者是空串。
- @Length: 判断字符的长度(最大或者最小)
- @Min: 判断数值最小值
- @Max: 判断数值最大值
- @Email: 判断邮箱是否合法