Spring Boot 使用@Validated校驗參數

背景說明:

後端開發中,參數校驗是必不可少的一個環節;寫起來比較繁瑣,這裏就用@Validated來處理參數校驗.這裏以獲取驗證碼接口爲例

1.使用Maven創建一個Spring Boot項目

Spring Boot項目HelloWord

2.在.pom文件中引入相關依賴:

 <!--  參數校驗-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
        

3.定義一個對象


/**
 * 請求獲取驗證碼
 */
public class RequestVerificationCode {
    //進行非空判斷
    @NotEmpty(message = "國際區號不能爲空")
    public String countrycode;  //用戶手機號碼國家碼


    //進行非空判斷
    //添加正則表達式校驗
    @NotEmpty(message = "手機號碼不能爲空")
    @Pattern(regexp = "^[1][3,4,5,7,8,9][0-9]{9}$", message = "手機號碼不合法")
    public String mobile;  //用戶手機號碼

    public String getCountrycode() {
        return countrycode;
    }

    public void setCountrycode(String countrycode) {
        this.countrycode = countrycode;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

}

4.Controller類中編寫接口

  /**
     * 請求獲取驗證碼
     *POST方法中接收剛纔我們寫的RequestVerificationCode,使用@Validated類
     * @param req
     * @return
     */
    @RequestMapping(value = "requestVerificationCode", method = RequestMethod.POST)
    public BaseResponse requestVerificationCode(@RequestBody @Validated RequestVerificationCode req) {
        return userServices.requestVerificationCode(req);
    }

5.當參數校驗失敗時會拋出異常MethodArgumentNotValidException

6.統一處理異常,增加異常處理的類


@ControllerAdvice
public class ExceptionHandle {

    /**
     * 捕獲參數異常
     *
     * @param exception MethodArgumentNotValidException
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public BaseResponse argumentException(MethodArgumentNotValidException exception) {
        String resut = "";
        //查看MethodArgumentNotValidException類可以發現,異常的信息在BindingResult下List<ObjectError>中
        //我這裏取第一條的信息進行展示,可根據實際項目情況自行修改
        //getDefaultMessage()獲取的信息就是我們RequestVerificationCode中的message部分
        if (exception.getBindingResult() != null
                && exception.getBindingResult().getAllErrors() != null
                && exception.getBindingResult().getAllErrors().size() > 0) {
            resut = exception.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        }
        //自定義的返回類,可根據實際項目情況自行修改
        BaseResponse response = new BaseResponse();
        response.setRsbCode(RsbCode.Rsb_Error_RequestJson, resut);
        return response;
    }


    /**
     * 全局捕獲異常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public BaseResponse handle(Exception e) {
        BaseResponse response = new BaseResponse();
        response.setRsbCode(RsbCode.Rsb_SYS_ERR, e.getMessage());
        return response;
    }


}


7.GET請求時校驗參數

注意:

  • 首先將@Validated註解加載Controller上
  • 校驗失敗時返回的異常爲ConstraintViolationException
//
//


   /**
     * 請求獲取驗證碼
     *
     * @param countrycode
     * @param mobile
     * @return
     */
    @GetMapping(value = "requestVerificationCode")
    public BaseResponse requestVerificationCode(
            @NotEmpty(message = "國際區號不能爲空")
            @RequestParam String countrycode,
            @NotEmpty(message = "手機號碼不能爲空")
            @Pattern(regexp = "^[1][3,4,5,7,8,9][0-9]{9}$", message = "手機號碼不合法")
            @RequestParam String mobile) {
        return userServices.requestVerificationCode(countrycode, mobile);
    }
    

8.運行項目,進行測試

測試請求的數據

{
  "countrycode": "",
  "mobile": "13333333333"
}

響應數據

{
  "resb": 400,
  "resbInfo": "國際區號不能爲空"
}

請求數據

{
  "countrycode": "86",
  "mobile": "123456789"
}

返回數據

{
  "resb": 400,
  "resbInfo": "手機號碼不合法"
}

附錄註解說明:

@Null                           被註釋的元素必須爲 null    
@NotNull                        被註釋的元素必須不爲 null    
@AssertTrue                     被註釋的元素必須爲 true    
@AssertFalse                    被註釋的元素必須爲 false    
@Min(value)                     被註釋的元素必須是一個數字,其值必須大於等於指定的最小值
@Max(value)                     被註釋的元素必須是一個數字,其值必須小於等於指定的最大值    
@DecimalMin(value)              被註釋的元素必須是一個數字,其值必須大於等於指定的最小值    
@DecimalMax(value)              被註釋的元素必須是一個數字,其值必須小於等於指定的最大值    
@Size(max=, min=)               被註釋的元素的大小必須在指定的範圍內    
@Digits (integer, fraction)     被註釋的元素必須是一個數字,其值必須在可接受的範圍內    
@Past                           被註釋的元素必須是一個過去的日期    
@Future                         被註釋的元素必須是一個將來的日期    
@Pattern(regex=,flag=)           被註釋的元素必須符合指定的正則表達式    


Hibernate Validator提供的校驗註解:  
@NotBlank(message =)            驗證字符串非null,且trim後長度必須大於0    
@Email                          被註釋的元素必須是電子郵箱地址    
@Length(min=,max=)              被註釋的字符串的大小必須在指定的範圍內    
@NotEmpty                       被註釋的字符串的必須非空    
@Range(min=,max=,message=)      被註釋的元素必須在合適的範圍內

@AssertFalse                    校驗false  
@AssertTrue                     校驗true  
@DecimalMax(value=,inclusive=)  小於等於value,  
inclusive=true,是小於等於  
@DecimalMin(value=,inclusive=)  與上類似  
@Max(value=)                    小於等於value  
@Min(value=)                    大於等於value  
@NotNull                        檢查Null  
@Past                           檢查日期  
@Pattern(regex=,flag=)           正則  
@Size(min=, max=)               字符串,集合,map限制大小  
@Valid                          對po實體類進行校驗
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章