1-7SpringBoot之表單驗證@Valid


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

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

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

我們先新建一個Student實體

import javax.persistence.Column;

import  javax.persistence.Entity;
import  javax.persistence.GeneratedValue;
import  javax.persistence.Id;
import  javax.persistence.Table;
import  javax.validation.constraints.Min;
import  javax.validation.constraints.NotNull;
 
@Entity
@Table (name= "t_student" )
public  class  Student {
 
     @Id
     @GeneratedValue
     private  Integer id;
     
     @NotEmpty (message= "姓名不能為空!" )
     @Column (length= 50 )
     private  String name;
     
     @NotNull (message= "年齡不能為空!" )
     @Min (value= 18 ,message= "年齡必須大於18歲!" )
     @Column (length= 50 )
     private  Integer age;
 
     public  Integer getId() {
         return  id;
     }
 
     public  void  setId(Integer id) {
         this .id = id;
     }
 
     public  String getName() {
         return  name;
     }
 
     public  void  setName(String name) {
         this .name = name;
     }
 
     public  Integer getAge() {
         return  age;
     }
 
     public  void  setAge(Integer age) {
         this .age = age;
     }
     
}
 

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

限制 說明
@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格式

 

 

dao接口寫下:

 

import org.springframework.data.jpa.repository.JpaRepository;

 
import  com.java1234.entity.Student;
 
/**
  * 學生Dao接口
  * @author user
  *
  */
public  interface  StudentDao  extends  JpaRepository<Student, Integer>{
 
}
 
service接口寫下:
 
import  com.java1234.entity.Student;
 
/**
  * 學生Service接口
  * @author user
  *
  */
public  interface  StudentService {
 
     /**
      * 添加學生
      */
     public  void  add(Student student);
}
 
service接口實現類寫下:
 
import  javax.annotation.Resource;
 
import  org.springframework.stereotype.Service;
 
import  com.java1234.dao.StudentDao;
import  com.java1234.entity.Student;
import  com.java1234.service.StudentService;
 
/**
  * 學生Service實現類
  * @author user
  *
  */
@Service
public  class  StudentServiceImpl  implements  StudentService{
 
     @Resource
     private  StudentDao studentDao;
 
     @Override
     public  void  add(Student student) {
         studentDao.save(student);
     }
}
 
controller寫下:
 
import  javax.annotation.Resource;
import  javax.validation.Valid;
 
import  org.springframework.stereotype.Controller;
import  org.springframework.validation.BindingResult;
import  org.springframework.web.bind.annotation.PostMapping;
import  org.springframework.web.bind.annotation.RequestMapping;
import  org.springframework.web.bind.annotation.ResponseBody;
import  org.springframework.web.bind.annotation.RestController;
import  org.springframework.web.servlet.ModelAndView;
 
import  com.java1234.entity.Student;
import  com.java1234.service.StudentService;
 
/**
  * 學生控制類
  * @author user
  *
  */
@RestController
@RequestMapping ( "/student" )
public  class  StudentController {
 
     @Resource
     private  StudentService studentService;
     
     /**
      * 添加圖書
      * @param book
      * @return
      */
     @ResponseBody
     @PostMapping (value= "/add" )
     public  String add( @Valid  Student student,BindingResult bindingResult){
         if (bindingResult.hasErrors()){
             return  bindingResult.getFieldError().getDefaultMessage();
         } else {
             studentService.add(student);
             return  "添加成功!" ;
         }
     }
}
 

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

 

student添加頁面studentAdd.html

 

 

<!DOCTYPE html>

< html >
< head >
< meta  charset = "UTF-8" >
< title >學生信息添加頁面</ title >
< script  src = "jQuery.js" ></ script >
< script  type = "text/javascript" >
     function submitData(){
         $.post("/student/add",{name:$("#name").val(),age:$("#age").val()},
                 function(result){
                     alert(result);
                 }
         );
     }
</ script >
</ head >
< body >
姓名:< input  type = "text"  id = "name"  name = "name" />
年齡:< input  type = "text"  id = "age"  name = "age" />
< input  type = "button"  value = "提交"  onclick = "submitData()" />
</ body >
</ html >
 
 
 

 

 

 

直接點擊提交

 

輸入姓名后,提交

 

 

輸入年齡5,提交

 

 

我們改成20,提交

 

 提交通過。

 


免責聲明!

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



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