本文記錄學習在SpringBoot中做數據校驗。
一 什么是數據校驗
數據校驗就是在應用程序中,對輸入進來得數據做語義分析判斷,阻擋不符合規則得數據,放行符合規則得數據,以確保被保存得數據符合我們得數據存儲規則。
在SpringMvc中做數據校驗有2中方式:一種是 Spring 自帶的驗證框架,另外一種是利用 JSR 實現。JSR 是一個規范,提供了完整得一套 API,通過標注給對象屬性添加約束。Hibernate Validator 就是 對JSR 規范所有注解的具體實現,以及一些附加的約束注解。用戶還可以自定義約束注解。Hibernate Validator提供得注解如下:
注解 | 作用目標 | 檢查規則 |
@Length(min=, max=) | 屬性(String) | 檢查字符串長度是否符合范圍 |
@Max(value=) | 屬性(以 numeric 或者 string 類型來表示一個數字) | 檢查值是否小於或等於最大值 |
@Min(value=) | 屬性(以 numeric 或者 string 類型來表示一個數字) | 檢查值是否大於或等於最小值 |
@NotNull | 屬性 | 檢查值是否非空(not null) |
@Future | 屬性(date 或 calendar) | 檢查日期是否是未來 |
@Pattern(regex="regexp", flag=) | 屬性(string) | 檢查屬性是否與給定匹配標志的正則表達式相匹配 |
@Range(min=, max=) | 屬性(以 numeric 或者 string 類型來表示一個數字) | 檢查值是否在最小和最大值之間(包括臨界值) |
@Size(min=, max=) | 屬性(array,collection,map) | 檢查元素大小是否在最小和最大值之間(包括臨界值) |
@AssertFalse | 屬性 | 檢查方法的演算結果是否為 false(對以代碼方式而不是注解表示的約束很有用) |
@AssertTrue | 屬性 | 檢查方法的演算結果是否為 true(對以代碼方式而不是注解表示的約束很有用) |
@Valid | 屬性(object) | 對關聯對象遞歸進行驗證。如果對象是集合或數組,就遞歸地驗證其元素;如果對象是 Map,則遞歸驗證其值元素 |
屬性(String) | 檢查字符串是否符合有效的 email 地址規范 | |
@Past | 屬性(date 或 calendar) | 檢查日期是否是過去 |
二 使用示例
SpringBoot對數據校驗也做了支持,默認提供的參數校驗依賴於 hibernate-validator來實現。使用 Hibernate Validator校驗數據,需要定義一個接收的數據模型,使用注解的形式描述字段校驗的規則。通過前台頁面提交form表單保存數據,后台做校驗。
在pom.xml文件中引入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
寫一個實體類,對相關屬性字段通過注解添加校驗規則
public class Person {
@NotBlank(message = "不能為空")
@Length(min = 2, max = 20, message = "長度要在2到20之間")
private String name;
@NotNull
@Min(value = 17, message = "最小值為17")
private Integer age;
@NotEmpty
@Email(message="郵件格式不正確")
private String email;
// 此處省略getter和setter
}
每個注解中得屬性message是數據校驗不通過時我們要給出得提示信息,如 @Email(message="郵件格式不正確") 當郵件格式校驗不通過時,提示郵件格式不正確。
控制器
@Controller public class TestController { @GetMapping("/info") public String info(Model model){ Person person = new Person(); model.addAttribute("person", person); return "person_info.html"; } @PostMapping("/save") public String save(@Valid Person person, BindingResult result, Model model){ if (result.hasErrors()) { model.addAttribute("person", person); return "person_info.html"; }
//數據保存。。。 model.addAttribute("success","校驗通過,數據已保存"); return "success.html"; } }
我們通過訪問info方法,跳轉到信息輸入頁面,提交數據時訪問save方法,Person前得注解@Valid 說明當前對象要做數據校驗,BindingResult 中會存儲數據校驗得結果,@Valid和BindingResult必須成對出現。如果校驗不通過時即有錯誤信息,會進入if略記判斷中,返回信息輸入頁面,展示錯誤提示信息。
信息輸入頁面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form th:action="@{/save}" th:method="post" th:object="${person}">
<table>
<tr>
<td>name:</td>
<td><input type="text" th:field="*{name}" th:value="${person.name}"/></td>
<td th:if="${#fields.hasErrors('name')}" th:errors="*{name}" th:style="'color:red'">Name Error</td>
</tr>
<tr>
<td>age:</td>
<td><input type="text" th:field="*{age}" th:value="${person.age}"/></td>
<td th:if="${#fields.hasErrors('age')}" th:errors="*{age}" th:style="'color:red'">Age Error</td>
</tr>
<tr>
<td>email:</td>
<td><input type="text" th:field="*{email}" th:value="${person.email}"/></td>
<td th:if="${#fields.hasErrors('email')}" th:errors="*{email}" th:style="'color:red'">Email Error</td>
</tr>
<tr>
<td th:colspan="2"><button th:type="submit">Submit</button></td>
</tr>
</table>
</form>
</body>
</html>
th:object 要與后台接收校驗得對象保持一致。訪問info方法在頁面隨便輸入一些信息,在提交數據,會看到校驗結果
如果各項數據都符合規則,則校驗通過,跳轉至success頁面