為什么需要引數校驗
在日常的介面開發中,為了防止非法引數對業務造成影響,經常需要對介面的引數進行校驗,例如登錄的時候需要校驗用戶名和密碼是否為空,添加用戶的時候校驗用戶郵箱地址、手機號碼格式是否正確, 靠代碼對介面引數一個個校驗的話就太繁瑣了,代碼可讀性極差,
Validator框架就是為了解決開發人員在開發的時候少寫代碼,提升開發效率;Validator專門用來進行介面引數校驗,例如常見的必填校驗,email格式校驗,用戶名必須位于6到12之間等等,
接下來我們看看在SpringbBoot中如何集成引數校驗框架,
SpringBoot中集成引數校驗
引入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
定義引數物體類
package com.didiplus.modules.sys.domain;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
/**
* Author: didiplus
* Email: [email protected]
* CreateTime: 2022/4/25
* Desc: 字典型別領域模型
*/
@Data
@ApiModel(value = "https://www.cnblogs.com/alanlin/p/字典型別")
public class SysDictType {
@ApiModelProperty("ID")
private String id;
@NotBlank(message = "字典名稱必填項")
@ApiModelProperty(value = "https://www.cnblogs.com/alanlin/p/字典名稱",example = "用戶ID")
private String typeName;
@NotBlank(message = "字典編碼不能為空")
@ApiModelProperty(value = "https://www.cnblogs.com/alanlin/p/字典編碼")
private String typeCode;
@Email(message = "請填寫正確的郵箱地址")
@ApiModelProperty(value = "https://www.cnblogs.com/alanlin/p/字典編碼")
private String email;
@ApiModelProperty(value = "https://www.cnblogs.com/alanlin/p/字典描述")
private String description;
@NotBlank(message = "字典狀態不能為空")
@ApiModelProperty(value = "https://www.cnblogs.com/alanlin/p/字典狀態")
private String enable;
}
常見的約束注解如下:
| 注解 | 功能 |
|---|---|
| @AssertFalse | 可以為null,如果不為null的話必須為false |
| @AssertTrue | 可以為null,如果不為null的話必須為true |
| @DecimalMax | 設定不能超過最大值 |
| @DecimalMin | 設定不能超過最小值 |
| @Digits | 設定必須是數字且數字整數的位數和小數的位數必須在指定范圍內 |
| @Future | 日期必須在當前日期的未來 |
| @Past | 日期必須在當前日期的過去 |
| @Max | 最大不得超過此最大值 |
| @Min | 最大不得小于此最小值 |
| @NotNull | 不能為null,可以是空 |
| @Null | 必須為null |
| @Pattern | 必須滿足指定的正則運算式 |
| @Size | 集合、陣列、map等的size()值必須在指定范圍內 |
| 必須是email格式 | |
| @Length | 長度必須在指定范圍內 |
| @NotBlank | 字串不能為null,字串trim()后也不能等于"" |
| @NotEmpty | 不能為null,集合、陣列、map等size()不能為0;字串trim()后可以等于"" |
| @Range | 值必須在指定范圍內 |
| @URL | 必須是一個URL |
定義校驗類進行測驗
package com.didiplus.modules.sys.controller;
import com.didiplus.modules.sys.domain.SysDictType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Author: didiplus
* Email: [email protected]
* CreateTime: 2022/4/25
* Desc: 資料字典控制器
*/
@RestController
@Api(tags = "資料字典")
@RequestMapping("/api/sys/dictType")
public class SysDictTypeController {
@ApiOperation("字典添加")
@PostMapping("/add")
public SysDictType add(@Validated @RequestBody SysDictType sysDictType) {
return sysDictType;
}
@ApiOperation("字典修改")
@PutMapping("/edit")
public SysDictType edit(@Validated @RequestBody SysDictType sysDictType) {
return sysDictType;
}
}
這里我們先定義兩個方法add,edit,都是使用了 @RequestBody注解,用于接受前端發送的json資料,
打開介面檔案模擬提交資料

通過介面檔案看到前三個欄位都是必填項,

由于email的格式不對就被攔截了,提示是因為郵箱地址不對,
引數例外加入全域例外處理器
雖然我們之前定義了全域例外攔截器,也看到了攔截器確實生效了,但是 Validator校驗框架回傳的錯誤提示太臃腫了,不便于閱讀,為了方便前端提示,我們需要將其簡化一下,
直接修改之前定義的 RestExceptionHandler,單獨攔截引數校驗的三個例外:javax.validation.ConstraintViolationException,org.springframework.validation.BindException,org.springframework.web.bind.MethodArgumentNotValidException,代碼如下:
package com.didiplus.common.web.response.Handler;
import com.didiplus.common.web.response.Result;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.stream.Collectors;
/**
* Author: didiplus
* Email: [email protected]
* CreateTime: 2022/4/24
* Desc: 默認全域例外處理,
*/
@RestControllerAdvice
public class RestExceptionHandler {
/**
* 默認全域例外處理,
* @param e the e
* @return ResultData
*/
@ExceptionHandler(value = https://www.cnblogs.com/alanlin/p/{BindException.class, ValidationException.class, MethodArgumentNotValidException.class})
public ResponseEntity> handleValidatedException(Exception e) {
Result result = null;
if (e instanceof MethodArgumentNotValidException) {
MethodArgumentNotValidException ex =(MethodArgumentNotValidException) e;
result = Result.failure(HttpStatus.BAD_REQUEST.value(),
ex.getBindingResult().getAllErrors().stream()
.map(ObjectError::getDefaultMessage)
.collect(Collectors.joining(";"))
);
} else if (e instanceof ConstraintViolationException){
ConstraintViolationException ex = (ConstraintViolationException) e;
result = Result.failure(HttpStatus.BAD_REQUEST.value(),
ex.getConstraintViolations().stream()
.map(ConstraintViolation::getMessage)
.collect(Collectors.joining(";"))
);
}else if (e instanceof BindException) {
BindException ex = (BindException ) e;
result = Result.failure(HttpStatus.BAD_REQUEST.value(),
ex.getAllErrors().stream()
.map(ObjectError::getDefaultMessage)
.collect(Collectors.joining(";"))
);
}
return new ResponseEntity<>(result,HttpStatus.BAD_REQUEST);
}
}
美化之后錯誤資訊提示更加友好,

自定義引數校驗
雖然Spring Validation 提供的注解基本上夠用,但是面對復雜的定義,我們還是需要自己定義相關注解來實作自動校驗,
比如上面物體類中添加的sex性別屬性,只允許前端傳遞傳 M,F 這2個列舉值,如何實作呢?
創建自定義注解
package com.didiplus.common.annotation;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Author: didiplus
* Email: [email protected]
* CreateTime: 2022/4/26
* Desc:
*/
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
@Retention(RUNTIME)
@Repeatable(EnumString.List.class)
@Documented
@Constraint(validatedBy = EnumStringValidator.class)//標明由哪個類執行校驗邏輯
public @interface EnumString {
String message() default "value not in enum values.";
Class<?>[] groups() default {};
Class<? extends Payload>[] palyload() default {};
/**
* @return date must in this value array
*/
String[] value();
/**
* Defines several {@link EnumString} annotations on the same element.
*
* @see EnumString
*/
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
@Retention(RUNTIME)
@Documented
@interface List {
EnumString[] value();
}
}
自定義校驗邏輯
package com.didiplus.common.annotation;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.List;
/**
* Author: didiplus
* Email: [email protected]
* CreateTime: 2022/4/26
* Desc:
*/
public class EnumStringValidator implements ConstraintValidator<EnumString,String> {
private List<String> enumStringList;
@Override
public void initialize(EnumString constraintAnnotation) {
enumStringList = Arrays.asList(constraintAnnotation.value());
}
@Override
public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
if(value =https://www.cnblogs.com/alanlin/p/= null) {
return true;
}
return enumStringList.contains(value);
}
}
在欄位上增加注解
@ApiModelProperty(value = "https://www.cnblogs.com/alanlin/p/性別")
@EnumString(value = https://www.cnblogs.com/alanlin/p/{"F","M"}, message="性別只允許為F或M")
private String sex;
體驗效果

分組校驗
一個物件在新增的時候某些欄位是必填,在更新是有非必填,如上面的 SysDictType中 id 屬性在新增操作時都是必填, 面對這種場景你會怎么處理呢?
其實 Validator校驗框架已經考慮到了這種場景并且提供了解決方案,就是分組校驗, 要使用分組校驗,只需要三個步驟:
定義分組介面
package com.didiplus.common.base;
import javax.validation.groups.Default;
/**
* Author: didiplus
* Email: [email protected]
* CreateTime: 2022/4/26
* Desc:
*/
public interface ValidGroup extends Default {
interface Crud extends ValidGroup{
interface Create extends Crud{
}
interface Update extends Crud{
}
interface Query extends Crud{
}
interface Delete extends Crud{
}
}
}
在模型中給引數分配分組
@Null(groups = ValidGroup.Crud.Create.class)
@NotNull(groups = ValidGroup.Crud.Update.class,message = "字典ID不能為空")
@ApiModelProperty("ID")
private String id;
體現效果


本文來自博客園,作者:北根娃,轉載請注明原文鏈接:https://www.cnblogs.com/alanlin/p/16198128.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/465944.html
標籤:Java
