spring mvc 校驗@NULL @notNULL等

一、準備校驗時使用的JAR

 

[java] view plain copy
 
  1. validation-api-1.0.0.GA.jar:JDK的接口;  
  2. hibernate-validator-4.2.0.Final.jar是對上述接口的實現;  
  3. log4j、slf4j、slf4j-log4j  

 

二、編寫需要校驗的bean

@NotNull(message="名字不能爲空")
private String userName;
@Max(value=120,message="年齡最大不能查過120")
private int age;
@Email(message="郵箱格式錯誤")
private String email;

 

三、校驗方法

 

    @RequestMapping("/login")
    public String testValid(@Valid User user, BindingResult result){
        if (result.hasErrors()){
            List<ObjectError> errorList = result.getAllErrors();
            for(ObjectError error : errorList){
                System.out.println(error.getDefaultMessage());
            }
        }
           
        return "test";
    }

 

備註:這裏一個@Valid的參數後必須緊挨着一個BindingResult 參數,否則spring會在校驗不通過時直接拋出異常


校驗註解

1 空檢查

[java] view plain copy
 
  1. @Null   驗證對象是否爲null  
  2. @NotNull驗證對象是否不爲null, 無法查檢長度爲0的字符串  
  3. @NotBlank 檢查約束字符串是不是Null還有被Trim的長度是否大於0,只對字符串,且會去掉前後空格.  
  4. @NotEmpty 檢查約束元素是否爲NULL或者是EMPTY,用在集合類上面
1.@NotNull:不能爲null,但可以爲empty(""," ","   ")   
2.@NotEmpty:不能爲null,而且長度必須大於0(" ","  ")
3.@NotBlank:只能作用在String上,不能爲null,而且調用trim()後,長度必須大於0, ("test") 即:必須有實際字符

@NotNull: The CharSequence, Collection, Map or Array object is not null,but can be empty.
@NotEmpty: The CharSequence, Collection, Map or Array object is not null and size > 0.
@NotBlank: The string is not null and the trimmed length is greater thanzero.

Examples:
[java] view plain copy
 
  1. 1.String name = null;  
  2. @NotNullfalse  
  3. @NotEmpty:false   
  4. @NotBlank:false   
  5.   
  6. 2.String name = "";  
  7. @NotNull:true  
  8. @NotEmptyfalse  
  9. @NotBlankfalse  
  10.   
  11. 3.String name = " ";  
  12. @NotNulltrue  
  13. @NotEmptytrue  
  14. @NotBlankfalse  
  15.   
  16. 4.String name = "Great answer!";  
  17. @NotNulltrue  
  18. @NotEmpty:true  
  19. @NotBlank:true  

Booelan檢查

[java] view plain copy
 
  1. @AssertTrue 驗證 Boolean 對象是否爲 true   
  2. @AssertFalse驗證 Boolean 對象是否爲 false   

長度檢查

[java] view plain copy
 
  1. @Size(min=, max=) 驗證對象(Array,Collection,Map,String)長度是否在給定的範圍之內。可以驗證集合內元素的多少。  
  2. @Length(min=, max=) Validates that the annotated string is between min and max included.主要用於String類型  

日期檢查

 

[java] view plain copy
 
  1. @Past   驗證 Date 和 Calendar 對象是否在當前時間之前    
  2. @Future 驗證 Date 和 Calendar 對象是否在當前時間之後    
  3. @Pattern驗證 String 對象是否符合正則表達式的規則  

 

數值檢查

建議使用在Stirng,Integer類型,不建議使用在int類型上,
因爲表單值爲“”時無法轉換爲int,但可以轉換爲Stirng爲"",Integer爲null

[html] view plain copy
 
  1. @Min            驗證 Number 和 String 對象是否大等於指定的值    
  2. @Max            驗證 Number 和 String 對象是否小等於指定的值    
  3. @DecimalMax 被標註的值必須不大於約束中指定的最大值. 這個約束的參數是一個通過BigDecimal定義的最大值的字符串表示.小數存在精度  
  4. @DecimalMin 被標註的值必須不小於約束中指定的最小值. 這個約束的參數是一個通過BigDecimal定義的最小值的字符串表示.小數存在精度  
  5. @Digits     驗證 Number 和 String 的構成是否合法    
  6. @Digits(integer=,fraction=) 驗證字符串是否是符合指定格式的數字,interger指定整數精度,fraction指定小數精度。  

其他

[java] view plain copy
 
  1. @Valid 遞歸的對關聯對象進行校驗, 如果關聯對象是個集合或者數組,那麼對其中的元素進行遞歸校驗,如果是一個map,則對其中的值部分進行校驗.(是否進行遞歸驗證)  
  2. @CreditCardNumber信用卡驗證  
  3. @Email  驗證是否是郵件地址,如果爲null,不進行驗證,算通過驗證。  
  4. @ScriptAssert(lang= ,script=, alias=)  
  5. @URL(protocol=,host=, port=,regexp=, flags=)  
  6. @Range(min=, max=) Checks whether the annotated value lies between (inclusive) the specified minimum and maximum.  
  7. @Range(min=10000,max=50000,message="range.bean.wage")  

小結

       枚舉:@NotNull校驗是否爲空  值的正確性有框架判定
       引用:首先@NotNull判定是否爲空,然後@valid進行級聯校驗
       數值:@NotNull判斷是否爲空, 使用@size/@Max/@Min進行大小的控制
       日期:@NotNull校驗是否爲空  @DateTimeFormat結合jode可以固定日期的格式
                  對於日期的範圍 註解解決不了 需要寫方法判斷了
                 日期類型輸入純文本數字也是可以通過的  值得注意
       字符串:使用@NotBlank,而不是@NotNull、@NotEmpty,@NotBlan是2者的結合;使用@Length限制長度   
               對於其輸入的具體內容的控制 目前沒有好辦法


      @NotEmpty 用在集合類上面  不能爲null,而且長度必須大於0  (" ","  ")
      @NotBlank 用在String上面  只能作用在String上,不能爲null,而且調用trim()後,長度必須大於0 ("test")    即:必須有實際字符
      @NotNull    用在基本類型上  不能爲null,但可以爲empty  (""," ","   ") 
 

級聯校驗

[java] view plain copy
 
  1. public class ReportVO {  
  2.   
  3.     @NotNull(message = "舉報內容不能爲空")  
  4.     @Valid  
  5.     private ReportContent content;  
  6.   
  7.     @NotNull(message = "舉報信息不能爲空")  
  8.     @Valid  
  9.     private ReportInfo info;  
  10. }  
 
[java] view plain copy
 
  1. public class ReportInfo extends BaseTenantDomain<String> {  
  2.   
  3.     private String reportContentId;  
  4.   
  5.     @NotBlank(message = "舉報人id不能爲空")  
  6.     private String reportorId;  
  7.   
  8.     @NotNull(message = "舉報類型不能爲空")  
  9.     private ReportType reportType;  
  10.   
  11.     @NotBlank(message = "舉報詳細描述不能爲空")  
  12.     @Size(max=100, message = "舉報詳細描述不能超過100")  
  13.     private String desc;  
  14.   
  15.     private Date reportTime; // 舉報時間  
  16.     private Date dealTime; // 處理時間  
  17.   
  18. }  
[java] view plain copy
 
  1. public void report(@RequestBody @Valid ReportVO reportVo) {  
  2.     contentService.report(reportVo.getContent(), reportVo.getInfo());  
  3. }<span style="font-family:microsoft yahei;"><span style="font-size: 15px; line-height: 35px;">  
  4. </span></span>  
發佈了27 篇原創文章 · 獲贊 2 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章