Spring Boot學習之五(數據驗證)html
1.在com.example.beans下建立MyUserView.java文件,內容以下: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代碼完成;服務器驗證是整個應用阻止非法數據的最後防線,主要經過在應用中編程實現。git
其中@NotBland(message="{user.name.notBlank}")爲使用JSR303註解驗證。web
其它的註解內容,見後面正則表達式
2.在resources下新建ValidationMessages.properties文件。該文件用於顯示錯誤信息,內容以下:spring
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對模型對象進行驗證,app
4.在resources下建立user目錄,在該目錄下建立login.html文件,內容以下:post
<!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格式 |