SpringBoot之表單驗證Valid


 

SpringBoot提供了強大的表單驗證功能實現,給我們省去了寫驗證的麻煩;

這里我們給下實例,提交一個有姓名和年齡的表單添加功能,

要求姓名不能為空,年齡必須是不小於18 ;

我們先新建一個Student實體

Student.java

 1 package com.hik.entity;
 2 
 3 import javax.persistence.Column;
 4 import javax.persistence.Entity;
 5 import javax.persistence.GeneratedValue;
 6 import javax.persistence.Id;
 7 import javax.persistence.Table;
 8 import javax.validation.constraints.Min;
 9 import javax.validation.constraints.NotNull;
10 
11 import org.hibernate.validator.constraints.NotEmpty;
12 
13 @Entity//類對應實體
14 @Table(name="t_student")//實體映射的表
15 public class Student {
16     
17     @Id//主鍵
18     @GeneratedValue//主鍵生成策略
19     private Integer id;
20     
21     @NotEmpty(message="姓名不能為空!")//驗證注解的元素值不為null且不為空(字符串長度不為0、集合大小不為0)
22     @Column(length=50)//設置字段屬性
23     private String name;
24     
25     @NotNull(message="年齡不能為空!")//限制必須不為null
26     @Min(value=18,message="年齡必須大於18歲!")//限制必須為一個不小於指定值的數字
27     @Column(length=50)//設置字段屬性
28     private Integer age;
29 
30     public Integer getId() {
31         return id;
32     }
33 
34     public void setId(Integer id) {
35         this.id = id;
36     }
37 
38     public String getName() {
39         return name;
40     }
41 
42     public void setName(String name) {
43         this.name = name;
44     }
45 
46     public Integer getAge() {
47         return age;
48     }
49 
50     public void setAge(Integer age) {
51         this.age = age;
52     }
53     
54     
55 }
View Code

注意:整數都用包裝類Integer

這里只用了兩個注解,下面列下清單,平時可以參考用;

限制 說明
@Null 限制只能為null
@NotNull 限制必須不為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之間
@Past 驗證注解的元素值(日期類型)比當前時間早
@NotEmpty 驗證注解的元素值不為null且不為空(字符串長度不為0、集合大小不為0)
@NotBlank 驗證注解的元素值不為空(不為null、去除首位空格后長度為0),不同於@NotEmpty,@NotBlank只應用於字符串且在比較時會去除字符串的空格
@Email 驗證注解的元素值是Email,也可以通過正則表達式和flag指定自定義的email格式

StudentDao接口:

 1 package com.hik.dao;
 2 
 3 import org.springframework.data.jpa.repository.JpaRepository;
 4 
 5 import com.hik.entity.Student;
 6 
 7 /**
 8  * 學生Dao接口
 9  * @author jed
10  *
11  */
12 public interface StudentDao extends JpaRepository<Student, Integer>{
13 
14 }
View Code

StudentService接口寫下:

 1 package com.hik.service;
 2 
 3 import com.hik.entity.Student;
 4 
 5 /**
 6  * 學生Service接口
 7  * @author jed
 8  *
 9  */
10 public interface StudentService {
11 
12     public void add(Student student);
13 }
View Code

StudentServiceImpl接口實現類寫下:

 1 package com.hik.service.impl;
 2 
 3 import javax.annotation.Resource;
 4 
 5 import org.springframework.stereotype.Service;
 6 
 7 import com.hik.dao.StudentDao;
 8 import com.hik.entity.Student;
 9 import com.hik.service.StudentService;
10 
11 /**
12  * 學生Service實現類
13  * @author jed
14  *
15  */
16 @Service(value="studentService")
17 public class StudentServiceImpl implements StudentService{
18 
19     @Resource
20     private StudentDao studentDao;
21     @Override
22     public void add(Student student) {
23         studentDao.save(student);
24     }
25 
26 }
View Code

StudentController寫下:

 1 package com.hik.Controller;
 2 
 3 import javax.annotation.Resource;
 4 import javax.validation.Valid;
 5 
 6 import org.springframework.validation.BindingResult;
 7 import org.springframework.web.bind.annotation.PostMapping;
 8 import org.springframework.web.bind.annotation.RequestMapping;
 9 import org.springframework.web.bind.annotation.ResponseBody;
10 import org.springframework.web.bind.annotation.RestController;
11 
12 import com.hik.entity.Student;
13 import com.hik.service.StudentService;
14 
15 /**
16  * 學生控制類
17  * @author jed
18  *
19  */
20 @RestController
21 @RequestMapping("/student")
22 public class StudentController {
23     
24     @Resource
25     private StudentService studentService;
26 
27     /**
28      * 添加圖書
29      * @param student
30      * @param bindingResult
31      * @return
32      */
33     @ResponseBody
34     @PostMapping("/add")
35     public String add(@Valid Student student,BindingResult bindingResult) {
36         if(bindingResult.hasErrors()) {
37             return bindingResult.getFieldError().getDefaultMessage();
38         }else {
39             studentService.add(student);
40             return "添加成功!";
41         }
42     }
43 }
View Code

add方法里 實體前要加@Valid 假如字段驗證不通過,信息綁定到后面定義的BindingResult;

 

student添加頁面studentAdd.html

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta charset="UTF-8">
 5 <title>學生信息添加頁面</title>
 6 <script src="jquery-1.11.1.js"></script>
 7 <script type="text/javascript">
 8     function submitData(){
 9         $.post("/student/add",{name:$("#name").val(),age:$("#age").val()},
10                 function(result){
11                     alert(result);
12                 }
13         );
14     }
15 </script>
16 </head>
17 <body>
18 姓名:<input type="text" id="name" name="name"/>
19 年齡:<input type="text" id="age" name="age"/>
20 <input type="button" value="提交" onclick="submitData()"/>
21 </body>
22 </html>
View Code

瀏覽器請求:http://localhost/studentAdd.html

直接點擊提交

輸入年齡12后,提交

輸入大於18,輸入20,提交

輸入姓名后,提交

提交通過。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM