參數校驗(validator)

原文鏈接:https://mp.weixin.qq.com/s/88hQqYvCzvJOcgt0rqh03g

爲什麼要用validator

  • .javax.validation的一系列註解可以幫我們完成參數校驗,免去繁瑣的串行校驗

不然我們的代碼就像下面這樣:

  /**
     * 走串行校驗
     *
     * @param userVO
     * @return
     */
    @PostMapping("/save/serial")
    public Object save(@RequestBody UserVO userVO) {
        String mobile = userVO.getMobile();

        //手動逐個 參數校驗~ 寫法
        if (StringUtils.isBlank(mobile)) {
            return RspDTO.paramFail("mobile:手機號碼不能爲空");
        } else if (!Pattern.matches("^[1][3,4,5,6,7,8,9][0-9]{9}$", mobile)) {
            return RspDTO.paramFail("mobile:手機號碼格式不對");
        }

        //拋出自定義異常等~寫法
        if (StringUtils.isBlank(userVO.getUsername())) {
            throw new BizException(Constant.PARAM_FAIL_CODE, "用戶名不能爲空");
        }

        // 比如寫一個map返回
        if (StringUtils.isBlank(userVO.getSex())) {
            Map<String, Object> result = new HashMap<>(5);
            result.put("code", Constant.PARAM_FAIL_CODE);
            result.put("msg", "性別不能爲空");
            return result;
        }
        //.........各種寫法 ...
        userService.save(userVO);
        return RspDTO.success();
    }
  • 什麼是javax.validation

JSR303 是一套JavaBean參數校驗的標準,它定義了很多常用的校驗註解,我們可以直接將這些註解加在我們JavaBean的屬性上面(面向註解編程的時代),就可以在需要校驗的時候進行校驗了,在SpringBoot中已經包含在starter-web中,再其他項目中可以引用依賴,並自行調整版本:

        <!--jsr 303-->
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.1.0.Final</version>
        </dependency>
        <!-- hibernate validator-->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.2.0.Final</version>
        </dependency>

在這裏插入圖片描述

  • 註解說明
    @NotNull:不能爲null,但可以爲empty(""," “,” “)
    @NotEmpty:不能爲null,而且長度必須大於0 (” “,” ")
    @NotBlank:只能作用在String上,不能爲null,而且調用trim()後,長度必須大於0(“test”) 即:必須有實際字符
    在這裏插入圖片描述
    實戰演練
  • @Validated 聲明要檢查的參數
 /**
     * 走參數校驗註解
     *
     * @param userDTO
     * @return
     */
    @PostMapping("/save/valid")
    public RspDTO save(@RequestBody @Validated UserDTO userDTO) {
        userService.save(userDTO);
        return RspDTO.success();
    }
  • 對參數的字段進行註解標註


import lombok.Data;
import org.hibernate.validator.constraints.Length;

import javax.validation.constraints.*;
import java.io.Serializable;
import java.util.Date;

/**
 * @author LiJing
 * @ClassName: UserDTO
 * @Description: 用戶傳輸對象
 * @date 2019/7/30 13:55
 */
@Data
public class UserDTO implements Serializable {

    private static final long serialVersionUID = 1L;

    /*** 用戶ID*/
    @NotNull(message = "用戶id不能爲空")
    private Long userId;

    /** 用戶名*/
    @NotBlank(message = "用戶名不能爲空")
    @Length(max = 20, message = "用戶名不能超過20個字符")
    @Pattern(regexp = "^[\\u4E00-\\u9FA5A-Za-z0-9\\*]*$", message = "用戶暱稱限制:最多20字符,包含文字、字母和數字")
    private String username;

    /** 手機號*/
    @NotBlank(message = "手機號不能爲空")
    @Pattern(regexp = "^[1][3,4,5,6,7,8,9][0-9]{9}$", message = "手機號格式有誤")
    private String mobile;

    /**性別*/
    private String sex;

    /** 郵箱*/
    @NotBlank(message = "聯繫郵箱不能爲空")
    @Email(message = "郵箱格式不對")
    private String email;

    /** 密碼*/
    private String password;

    /*** 創建時間 */
    @Future(message = "時間必須是將來時間")
    private Date createTime;

}
  • 在全局校驗中增加校驗異常
    MethodArgumentNotValidException是springBoot中進行綁定參數校驗時的異常,需要在springBoot中處理,其他需要處理ConstraintViolationException異常進行處理.
    爲了優雅一點,我們將參數異常,業務異常,統一做了一個全局異常,將控制層的異常包裝到我們自定義的異常中.
    爲了優雅一點,我們還做了一個統一的結構體,將請求的code,和msg,data一起統一封裝到結構體中,增加了代碼的複用性
import com.boot.lea.mybot.dto.RspDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;


/**
 * @author LiJing
 * @ClassName: GlobalExceptionHandler
 * @Description: 全局異常處理器
 * @date 2019/7/30 13:57
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private static int DUPLICATE_KEY_CODE = 1001;
    private static int PARAM_FAIL_CODE = 1002;
    private static int VALIDATION_CODE = 1003;

    /**
     * 處理自定義異常
     */
    @ExceptionHandler(BizException.class)
    public RspDTO handleRRException(BizException e) {
        logger.error(e.getMessage(), e);
        return new RspDTO(e.getCode(), e.getMessage());
    }

    /**
     * 方法參數校驗
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public RspDTO handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        logger.error(e.getMessage(), e);
        return new RspDTO(PARAM_FAIL_CODE, e.getBindingResult().getFieldError().getDefaultMessage());
    }

    /**
     * ValidationException
     */
    @ExceptionHandler(ValidationException.class)
    public RspDTO handleValidationException(ValidationException e) {
        logger.error(e.getMessage(), e);
        return new RspDTO(VALIDATION_CODE, e.getCause().getMessage());
    }

    /**
     * ConstraintViolationException
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public RspDTO handleConstraintViolationException(ConstraintViolationException e) {
        logger.error(e.getMessage(), e);
        return new RspDTO(PARAM_FAIL_CODE, e.getMessage());
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public RspDTO handlerNoFoundException(Exception e) {
        logger.error(e.getMessage(), e);
        return new RspDTO(404, "路徑不存在,請檢查路徑是否正確");
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public RspDTO handleDuplicateKeyException(DuplicateKeyException e) {
        logger.error(e.getMessage(), e);
        return new RspDTO(DUPLICATE_KEY_CODE, "數據重複,請檢查後提交");
    }


    @ExceptionHandler(Exception.class)
    public RspDTO handleException(Exception e) {
        logger.error(e.getMessage(), e);
        return new RspDTO(500, "系統繁忙,請稍後再試");
    }
}
  • 測試

如下文:確實做到了參數校驗時返回異常信息和對應的code,方便了我們不再繁瑣的處理參數校驗
在ValidationMessages.properties 就是校驗的message,有着已經寫好的默認的message,且是支持i18n的,大家可以閱讀源碼賞析。

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章