Springboot中如何優雅進行字段校驗

差很少大半年沒寫文章了,終於將手頭上的事忙完了,能夠對外輸出了。前段時間提交代碼審覈,同事提了一個代碼規範缺陷:參數校驗應該放在controller層。到底應該如何作參數校驗呢

Controller層 VS Service層

去網上查閱了一些資料,通常推薦與業務無關的放在Controller層中進行校驗,而與業務有關的放在Service層中進行校驗。那麼如何將參數校驗寫的優雅美觀呢,若是都是if - else,就感受代碼寫的很low,還好有輪子可使用java

經常使用校驗工具類

使用Hibernate Validate

引入依賴正則表達式

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>4.3.1.Final</version> 
</dependency>

經常使用註解說明
|註解 | 說明 |
|:-| :-|
| @Length(min=,max=) | 檢查所屬的字段的長度是否在min和max之間,只能用於字符串 |
| @Range(min=,max=,message=) | 被註釋的元素必須在合適的範圍內 |
| @Max | 該字段的值只能小於或等於該值 |
| @Min | 該字段的值只能大於或等於該值 |
| @NotNull | 不能爲null |
| @NotBlank | 不能爲空,檢查時會將空格忽略 |
| @NotEmpty | 不能爲空,這裏的空是指空字符串 |
| @Pattern(regex=,flag=) | 被註釋的元素必須符合指定的正則表達式 |spring

使用姿式
須要搭配在Controller中搭配@Validated或@Valid註解一塊兒使用,@Validated和@Valid註解區別不是很大,通常狀況下任選一個便可,區別以下:
|註解| @Validated | @Valid |
|:-|:-| :-|
|所屬的包| 屬於org.springframework.validation.annotation包下的,是spring提供的 | 屬於javax.validation包下,是jdk給提供的 |
|是否支持分組和排序| 是 | 否|
雖然@Validated比@Valid更增強大,在@Valid之上提供了分組功能和驗證排序功能,不過在實際項目中一直沒有用到過
Hibernate-validate框架中的註解是須要加在實體中一塊兒使用的apache

  • 定義一個實體
public class DataSetSaveVO {
    //惟一標識符爲空
    @NotBlank(message = "user uuid is empty")
    //用戶名稱只能是字母和數字
    @Pattern(regexp = "^[a-z0-9]+$", message = "user names can only be alphabetic and numeric")
    @Length(max = 48, message = "user uuid length over 48 byte")
    private String userUuid;

    //數據集名稱只能是字母和數字
    @Pattern(regexp = "^[A-Za-z0-9]+$", message = "data set names can only be letters and Numbers")
    //文件名稱過長
    @Length(max = 48, message = "file name too long")
    //文件名稱爲空
    @NotBlank(message = "file name is empty")
    private String name;

    //數據集描述最多爲256字節
    @Length(max = 256, message = "data set description length over 256 byte")
    //數據集描述爲空
    @NotBlank(message = "data set description is null")
    private String description;
}

說明:message字段爲不符合校驗規則時拋出的異常信息app

  • Controller層中的方法
@PostMapping
public ResponseVO createDataSet(@Valid @RequestBody DataSetSaveVO dataSetVO) {
    return ResponseUtil.success(dataSetService.saveDataSet(dataSetVO));
}

說明:在校驗的實體DataSetSaveVO旁邊添加@Valid或@Validated註解框架

使用commons-lang3

引入依賴工具

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.4</version>
</dependency>

經常使用方法說明
|方法 | 說明 |
|:-| :-|
| CollectionUtils.isEmpty | 判斷集合是否爲空,爲null或者size==0,返回true |
| CollectionUtils.isNotEmpty | 判斷集合是否爲非空 |
| StringUtils.isEmpty | 判斷字符串是否爲空 |
| StringUtils.isNotEmpty | 判斷字符串是否非空 |
| StringUtils.isBlank | 判斷字符串是否爲空,爲null或者size==0或者只存在空白字符(如" "),則返回true |
| StringUtils.isNotBlank | 判斷字符串是否爲非空 |post

  • 測試代碼
//StringUtils.isEmpty
System.out.println(StringUtils.isEmpty(""));  //true
System.out.println(StringUtils.isEmpty("  "));  //false
//StringUtils.isNotEmpty
System.out.println(StringUtils.isNotEmpty(""));  //false
        
//StringUtils.isBlank
System.out.println(StringUtils.isBlank(""));  //true
System.out.println(StringUtils.isBlank(" "));  //true
//StringUtils.isNotBlank
System.out.println(StringUtils.isNotBlank(" "));  //false

List<Integer> emptyList = new ArrayList<>();
List<Integer> nullList = null;
List<Integer> notEmptyList = new ArrayList<>();
notEmptyList.add(1);

//CollectionUtils.isEmpty
System.out.println(CollectionUtils.isEmpty(emptyList));   //true
System.out.println(CollectionUtils.isEmpty(nullList));   //true
System.out.println(CollectionUtils.isEmpty(notEmptyList));   //false

//CollectionUtils.isNotEmpty
System.out.println(CollectionUtils.isNotEmpty(emptyList));   //false
System.out.println(CollectionUtils.isNotEmpty(nullList));   //false
System.out.println(CollectionUtils.isNotEmpty(notEmptyList));   //true
自定義註解

當上面的方面都沒法知足校驗的需求之後,能夠考慮使用自定義註解,如何寫一個自定義註解,能夠參考以前寫的文章:Spring自定義註解從入門到精通測試

相關文章
相關標籤/搜索