天天看點

Spring Boot 進行優雅的字段校驗,寫得太好了!

前段時間送出代碼稽核,同僚提了一個代碼規範缺陷:參數校驗應該放在controller層。到底應該如何做參數校驗呢

Controller層 VS Service層

去網上查閱了一些資料,一般推薦與業務無關的放在Controller層中進行校驗,而與業務有關的放在Service層中進行校驗。

那麼如何将參數校驗寫的優雅美觀呢,如果都是if - else,就感覺代碼寫的很low,還好有輪子可以使用

常用校驗工具類

使用Hibernate Validate

引入依賴

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

常用注解說明

Spring Boot 進行優雅的字段校驗,寫得太好了!

使用姿勢

Spring Boot 基礎就不介紹了,推薦下這個實戰教程:

https://www.javastack.cn/categories/Spring-Boot/

需要搭配在Controller中搭配@Validated或@Valid注解一起使用,@Validated和@Valid注解差別不是很大,一般情況下任選一個即可,差別如下:

Spring Boot 進行優雅的字段校驗,寫得太好了!

雖然@Validated比@Valid更加強大,在@Valid之上提供了分組功能和驗證排序功能,不過在實際項目中一直沒有用到過

Hibernate-validate架構中的注解是需要加在實體中一起使用的

定義一個實體

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字段為不符合校驗規則時抛出的異常資訊

  • 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>      

常用方法說明

Spring Boot 進行優雅的字段校驗,寫得太好了!

測試代碼

//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      

自定義注解

當上面的方面都無法滿足校驗的需求以後,可以考慮使用自定義注解。