Spring學習筆記(十四)

前言

        最近工做,畢業設計都忙瘋了,辭了工做如今終於有空餘時間能夠繼續總結了
java

Spring數據校驗

        Spring有本身的校驗框架,同時也支持JSR 303 的校驗,這裏主要介紹Spring使用JSR 303的校驗,Spring的校驗框架主要方法org.springframework.vaildation包中。須要注意,Spring並無提供JSR 303規範的實現,因此必須添加JSR303的實現者jar包(好比Hibernate Validator),Spring JSR 303 校驗使用至關簡單,只須要在須要驗證的Bean中加入驗證的註解,再在Sping MVC 方法入參時,在該Bean前面加上@Valid便可,例:
git

public Class user {
    private String userId;
    
    //使用正則表達式效驗,匹配4~30個數字或字母或下劃線的字符
    @Pattern(regexp="w{4, 30}")
    private String userName;
    
    //長度在8~20之間
    @Length(min=8, max=20)
    private String passWord;
    
    //時間必須是過去的時間
    @Past
    @DateTimeFormat(pattern="yyy-MM-dd")
    private Date createDate;
    
    //數據必須大於1000小於100000
    @DecimalMin(value="1000.00")
    @DeciamlMax(value="100000.00")
    @NumberFormat(pattern="#,###.##")
    private long salary;
}

Controller中:正則表達式

@Controller
public class UserController {
    
    @RequestMapping(value = "/user", method = RequestMethod.POST)
    public String addUser(@Valid User user, BindingResult result) {
       ......
    }
}

在Spring MVC將User對象綁定入參後會進行校驗,結果會放在後面的BindingResult或者Errors對象中。spring

注意:BindingResult或者Errors必須緊跟在須要驗證的Bean後面,若是其間有其餘的入參會直接報異常數組

用於效驗的Annotation:app

@AssertTrue / @AssertFalse 
框架

  • 驗證適用字段:booleanspa

  • 註解說明:驗證值是否爲true / false.net

  • 屬性說明:-設計


@DecimalMax / @DecimalMin 

  • 驗證適用字段:BigDecimal,BigInteger,String,byte,short,int,long

  • 註解說明:驗證值是否小於或者等於指定的小數值,要注意小數存在精度問題

  • 屬性說明:公共


@Digits 

  • 驗證適用字段:BigDecimal,BigInteger,String,byte,short,int,long

  • 註解說明:驗證值的數字構成是否合法

  • 屬性說明:integer:指定整數部分的數字的位數。fraction: 指定小數部分的數字的位數。


@Future / @Past 

  • 驗證適用字段:Date,Calendar

  • 註解說明:驗證值是否在當前時間以後 / 以前

  • 屬性說明:公共


@Max / @Min 

  • 驗證適用字段:BigDecimal,BigInteger,String,byte,short,int,long

  • 註解說明:驗證值是否小於或者等於指定的整數值

  • 屬性說明:公共


@NotNull / @Null 

  • 驗證適用字段:引用數據類型

  • 註解說明:驗證值是否爲非空 / 空

  • 屬性說明:公共


@Pattern 

  • 驗證適用字段:String

  • 註解說明:驗證值是否配備正則表達式

  • 屬性說明:regexp:正則表達式flags: 指定Pattern.Flag 的數組,表示正則表達式的相關選項。


@Size 

  • 驗證適用字段:String,Collection,Map,數組

  • 註解說明:驗證值是否知足長度要求

  • 屬性說明:max:指定最大長度,min:指定最小長度。

相關文章
相關標籤/搜索