作者:錦成同學
來源:juejin.im/post/5d3fbeb46fb9a06b317b3c48
很痛苦遇到大量的引數進行校驗,在業務中還要拋出例外或者不斷的回傳例外時的校驗資訊,在代碼中相當冗長,充滿了if-else這種校驗代碼,今天我們就來學習spring的javax.validation 注解式引數校驗,
1.為什么要用validator
javax.validation的一系列注解可以幫我們完成引數校驗,免去繁瑣的串行校驗
不然我們的代碼就像下面這樣:
// http://localhost:8080/api/user/save/serial
/**
* 走串行校驗
*
* @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();
}
這被大佬看見,一定說,都9102了還這么寫,然后被勸退了…..
2.什么是javax.validation
JSR303 是一套JavaBean引數校驗的標準,它定義了很多常用的校驗注解,我們可以直接將這些注解加在我們JavaBean的屬性上面(面向注解編程的時代),就可以在需要校驗的時候進行校驗了,
Spring Boot 基礎就不介紹了,推薦下這個實戰教程:
https://github.com/javastacks/spring-boot-best-practice
在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>

3.注解說明
-
@NotNull:不能為null,但可以為empty(""," "," ")
-
@NotEmpty:不能為null,而且長度必須大于0 (" "," ")
-
@NotBlank:只能作用在String上,不能為null,而且呼叫trim()后,長度必須大于0("test") 即:必須有實際字符

此處只列出Hibernate Validator提供的大部分驗證約束注解,請參考hibernate validator官方檔案了解其他驗證約束注解和進行自定義的驗證約束注解定義,
4.實戰演練
話不多說,直接走實踐路線,同樣使用的是SpringBoot的快速框架,
詳細代碼見:
https://github.com/leaJone/mybot
4.1. @Validated 宣告要檢查的引數
這里我們在控制器層進行注解宣告
/**
* 走引數校驗注解
*
* @param userDTO
* @return
*/
@PostMapping("/save/valid")
public RspDTO save(@RequestBody @Validated UserDTO userDTO) {
userService.save(userDTO);
return RspDTO.success();
}
4.2. 對引數的欄位進行注解標注
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;
}
4.3. 在全域校驗中增加校驗例外
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, "系統繁忙,請稍后再試");
}
}
4.4. 測驗
如下文:確實做到了引數校驗時回傳例外資訊和對應的code,方便了我們不再繁瑣的處理引數校驗,

在ValidationMessages.properties 就是校驗的message,有著已經寫好的默認的message,且是支持i18n的,大家可以閱讀原始碼賞析,
5.自定義引數注解
5.1. 比如我們來個 自定義身份證校驗 注解
@Documented
@Target({ElementType.PARAMETER, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = IdentityCardNumberValidator.class)
public @interface IdentityCardNumber {
String message() default "身份證號碼不合法";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
這個注解是作用在Field欄位上,運行時生效,觸發的是IdentityCardNumber這個驗證類,
- message 定制化的提示資訊,主要是從ValidationMessages.properties里提取,也可以依據實際情況進行定制
- groups 這里主要進行將validator進行分類,不同的類group中會執行不同的validator操作
- payload 主要是針對bean的,使用不多,
5.2. 然后自定義Validator
這個是真正進行驗證的邏輯代碼:
public class IdentityCardNumberValidator implements ConstraintValidator<IdentityCardNumber, Object> {
@Override
public void initialize(IdentityCardNumber identityCardNumber) {
}
@Override
public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
return IdCardValidatorUtils.isValidate18Idcard(o.toString());
}
}
IdCardValidatorUtils在專案原始碼中,可自行查看
5.3. 使用自定義的注解
@NotBlank(message = "身份證號不能為空")
@IdentityCardNumber(message = "身份證資訊有誤,請核對后提交")
private String clientCardNo;
5.4.使用groups的校驗
有的寶寶說同一個物件要復用,比如UserDTO在更新時候要校驗userId,在保存的時候不需要校驗userId,在兩種情況下都要校驗username,那就用上groups了:
先定義groups的分組介面Create和Update,
import javax.validation.groups.Default;
public interface Create extends Default {
}
import javax.validation.groups.Default;
public interface Update extends Default{
}
再在需要校驗的地方@Validated宣告校驗組
/**
* 走引數校驗注解的 groups 組合校驗
*
* @param userDTO
* @return
*/
@PostMapping("/update/groups")
public RspDTO update(@RequestBody @Validated(Update.class) UserDTO userDTO) {
userService.updateById(userDTO);
return RspDTO.success();
}
在DTO中的欄位上定義好groups = {}的分組型別
@Data
public class UserDTO implements Serializable {
private static final long serialVersionUID = 1L;
/*** 用戶ID*/
@NotNull(message = "用戶id不能為空", groups = Update.class)
private Long userId;
/**
* 用戶名
*/
@NotBlank(message = "用戶名不能為空")
@Length(max = 20, message = "用戶名不能超過20個字符", groups = {Create.class, Update.class})
@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 = "手機號格式有誤", groups = {Create.class, Update.class})
private String mobile;
/**
* 性別
*/
private String sex;
/**
* 郵箱
*/
@NotBlank(message = "聯系郵箱不能為空")
@Email(message = "郵箱格式不對")
private String email;
/**
* 密碼
*/
private String password;
/*** 創建時間 */
@Future(message = "時間必須是將來時間", groups = {Create.class})
private Date createTime;
}
注意:在宣告分組的時候盡量加上 extend javax.validation.groups.Default 否則,在你宣告@Validated(Update.class)的時候,就會出現你在默認沒添加groups = {}的時候的校驗組@Email(message = "郵箱格式不對"),會不去校驗,因為默認的校驗組是groups = {Default.class}.
5.5.restful風格用法
在多個引數校驗,或者@RequestParam 形式時候,需要在controller上加注@Validated,
@GetMapping("/get")
public RspDTO getUser(@RequestParam("userId") @NotNull(message = "用戶id不能為空") Long userId) {
User user = userService.selectById(userId);
if (user == null) {
return new RspDTO<User>().nonAbsent("用戶不存在");
}
return new RspDTO<User>().success(user);
}
@RestController
@RequestMapping("user/")
@Validated
public class UserController extends AbstractController {
....圣洛代碼...
6.總結
用起來很簡單,soEasy,重點參與的統一結構體回傳,統一引數校驗,是減少我們代碼大量的try catch 的法寶,我覺得在專案中,將例外處理好,并將例外做好日志管理,才是很好的升華,文章淺顯,只是一個菜鳥的進階筆記….
這里只是個人見解,技術菜,歡迎大佬不吝賜教……
近期熱文推薦:
1.1,000+ 道 Java面試題及答案整理(2022最新版)
2.勁爆!Java 協程要來了,,,
3.Spring Boot 2.x 教程,太全了!
4.20w 程式員紅包封面,快快領取,,,
5.《Java開發手冊(嵩山版)》最新發布,速速下載!
覺得不錯,別忘了隨手點贊+轉發哦!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/423528.html
標籤:Java
