Spring Boot學習之五(數據驗證)
1.在com.example.beans下創建MyUserView.java文件,內容如下:
package com.example.beans;
import javax.validation.constraints.NotBlank;
public class MyUserView {
private int id;
@NotBlank(message="{user.name.notBlank}")
private String name;
private String passwd;
數據驗證:分爲客戶端和服務器驗證,客戶端驗證主要是過濾正常用戶的誤操作,主要通過JavaScript代碼完成;服務器驗證是整個應用阻止非法數據的最後防線,主要通過在應用中編程實現。
其中@NotBland(message="{user.name.notBlank}")爲使用JSR303註解驗證。
其它的註解內容,見後面
2.在resources下新建ValidationMessages.properties文件。該文件用於顯示錯誤信息,內容如下:
user.name.notBlank=\u7528\u6237\u540d\u4e0d\u80fd\u4e3a\u7a7a
該文件內容是Unicode編碼(注意)
3.創建控制器,代碼如下
package com.example.demo.controller;
import com.example.beans.MyUserView;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class ValidationStudy {
@RequestMapping(value = "/login",method = RequestMethod.GET)
public String login(Model model){
MyUserView user=new MyUserView();
model.addAttribute("user",user);
return "/user/login";
}
@RequestMapping(value="/loginsave",method = RequestMethod.POST)
public String loginSave(@Validated MyUserView user, BindingResult result, Model model){
model.addAttribute("user",user);
if(result.hasErrors()){
String errorInfo=result.getFieldError().getDefaultMessage();
model.addAttribute("errorInfo",errorInfo);
return "/user/login";
}
return "/user/login";
}
}
在控制器類中,使用@Validated對模型對象進行驗證,
4.在resources下創建user目錄,在該目錄下創建login.html文件,內容如下:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/loginsave" method="post">
用戶名:<input type="text" name="name" th:value="${user.getName()}"/>
<br/><br/>
密碼:<input type="text" name="passwd" th:value="${user.getPasswd()}"/>
<br/><br/>
<input type="submit" value="確定"/>
</form>
<div id="errorInfo">
<h4 th:text="${errorInfo}">錯誤信息</h4>
</div>
</body>
</html>
5.運行測試結果如下:
6.註解
@Null | 限制只能爲null |
@NotNull | dD限制必須不爲null |
@AssertFalse | 限制必須爲false |
@AssertTrue | 限制必須爲true |
@DecimalMax(value) | 限制必須爲一個不大於指定值 |
@DecimalMin(value) | 限制必須爲一個不小於指定值的數字 |
@Digits(integer,fraction) | 限制必須爲一個小數,且整數部分的位數不能超過integer,小數部分的位數不能超過fraction |
@Future | 限制必須是一個將來的日期 |
@Max(value) | 限制必須爲一個不大於指定值的數字 |
@Min(value) | 限制必須爲一個不小於指定值的數字 |
@Past | 限制必須是一個過去的日期 |
@Pattern(value) | 限制必須符合指定的正則表達式 |
@Size(max,min) | 限制字符長度必須在min到max之間 |
@NoteEmpty | 驗證註解的元素值不爲null且不爲空(字符串長度不爲0、集合大小不爲0) |
@NotBlank | 驗證註解的元素值不爲空(不爲null、去除首位空格後長度爲0),不同於@NotEmpty,@NotBlank只應用於字符串且在比較時會去除字符串的空格 |
|
驗證註解的元素值是Email,也可以通過正則表達式和flag指定自定義的email格式 |