資料的校驗的重要性就不用說了,即使在前端對資料進行校驗的情況下,我們還是要對傳入后端的資料再進行一遍校驗,避免用戶繞過瀏覽器直接通過一些 HTTP 工具直接向后端請求一些違法資料,
最普通的做法就像下面這樣,我們通過 if/else 陳述句對請求的每一個引數一一校驗,
@RestController
@RequestMapping("/api/person")
public class PersonController {
@PostMapping
public ResponseEntity<PersonRequest> save(@RequestBody PersonRequest personRequest) {
if (personRequest.getClassId() == null
|| personRequest.getName() == null
|| !Pattern.matches("(^Man$|^Woman$|^UGM$)", personRequest.getSex())) {
}
return ResponseEntity.ok().body(personRequest);
}
}
這樣的代碼,小伙伴們在日常開發中一定不少見,很多開源專案都是這樣對請求入參做校驗的,
但是,不太建議這樣來寫,這樣的代碼明顯違背了 單一職責原則,大量的非業務代碼混雜在業務代碼中,非常難以維護,還會導致業務層代碼冗雜!
實際上,我們是可以通過一些簡單的手段對上面的代碼進行改進的!這也是本文主要要介紹的內容!
廢話不多說!下面我會結合自己在專案中的實際使用經驗,通過實體程式演示如何在 SpringBoot 程式中優雅地的進行引數驗證(普通的 Java 程式同樣適用),
不了解的朋友一定要好好看一下,學完馬上就可以實踐到專案上去,
并且,本文示例專案使用的是目前最新的 Spring Boot 版本 2.4.5!(截止到 2021-04-21)
示例專案源代碼地址:https://github.com/CodingDocs/springboot-guide/tree/master/source-code/bean-validation-demo ,
添加相關依賴
如果開發普通 Java 程式的的話,你需要可能需要像下面這樣依賴:
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.9.Final</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.6</version>
</dependency>
不過,相信大家都是使用的 Spring Boot 框架來做開發,
基于 Spring Boot 的話,就比較簡單了,只需要給專案添加上 spring-boot-starter-web 依賴就夠了,它的子依賴包含了我們所需要的東西,另外,我們的示例專案中還使用到了 Lombok,

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
但是!!! Spring Boot 2.3 1 之后,spring-boot-starter-validation 已經不包括在了 spring-boot-starter-web 中,需要我們手動加上!

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
驗證 Controller 的輸入
驗證請求體
驗證請求體即使驗證被 @RequestBody 注解標記的方法引數,
PersonController
我們在需要驗證的引數上加上了@Valid注解,如果驗證失敗,它將拋出MethodArgumentNotValidException,默認情況下,Spring 會將此例外轉換為 HTTP Status 400(錯誤請求),
@RestController
@RequestMapping("/api/person")
@Validated
public class PersonController {
@PostMapping
public ResponseEntity<PersonRequest> save(@RequestBody @Valid PersonRequest personRequest) {
return ResponseEntity.ok().body(personRequest);
}
}
PersonRequest
我們使用校驗注解對請求的引數進行校驗!
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class PersonRequest {
@NotNull(message = "classId 不能為空")
private String classId;
@Size(max = 33)
@NotNull(message = "name 不能為空")
private String name;
@Pattern(regexp = "(^Man$|^Woman$|^UGM$)", message = "sex 值不在可選范圍")
@NotNull(message = "sex 不能為空")
private String sex;
}
正則運算式說明:
^string: 匹配以 string 開頭的字串string$:匹配以 string 結尾的字串^string$:精確匹配 string 字串(^Man$|^Woman$|^UGM$): 值只能在 Man,Woman,UGM 這三個值中選擇
GlobalExceptionHandler
自定義例外處理器可以幫助我們捕獲例外,并進行一些簡單的處理,如果對于下面的處理例外的代碼不太理解的話,可以查看這篇文章 《SpringBoot 處理例外的幾種常見姿勢》,
@ControllerAdvice(assignableTypes = {PersonController.class})
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, String>> handleValidationExceptions(
MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getAllErrors().forEach((error) -> {
String fieldName = ((FieldError) error).getField();
String errorMessage = error.getDefaultMessage();
errors.put(fieldName, errorMessage);
});
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errors);
}
}
通過測驗驗證
下面我通過 MockMvc 模擬請求 Controller 的方式來驗證是否生效,當然了,你也可以通過 Postman 這種工具來驗證,
@SpringBootTest
@AutoConfigureMockMvc
public class PersonControllerTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private ObjectMapper objectMapper;
/**
* 驗證出現引數不合法的情況拋出例外并且可以正確被捕獲
*/
@Test
public void should_check_person_value() throws Exception {
PersonRequest personRequest = PersonRequest.builder().sex("Man22")
.classId("82938390").build();
mockMvc.perform(post("/api/personRequest")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(personRequest)))
.andExpect(MockMvcResultMatchers.jsonPath("sex").value("sex 值不在可選范圍"))
.andExpect(MockMvcResultMatchers.jsonPath("name").value("name 不能為空"));
}
}
使用 Postman 驗證

驗證請求引數
驗證請求引數(Path Variables 和 Request Parameters)即是驗證被 @PathVariable 以及 @RequestParam 標記的方法引數,
PersonController
一定一定不要忘記在類上加上 Validated 注解了,這個引數可以告訴 Spring 去校驗方法引數,
@RestController
@RequestMapping("/api/persons")
@Validated
public class PersonController {
@GetMapping("/{id}")
public ResponseEntity<Integer> getPersonByID(@Valid @PathVariable("id") @Max(value = 5, message = "超過 id 的范圍了") Integer id) {
return ResponseEntity.ok().body(id);
}
@PutMapping
public ResponseEntity<String> getPersonByName(@Valid @RequestParam("name") @Size(max = 6, message = "超過 name 的范圍了") String name) {
return ResponseEntity.ok().body(name);
}
}
ExceptionHandler
@ExceptionHandler(ConstraintViolationException.class)
ResponseEntity<String> handleConstraintViolationException(ConstraintViolationException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
}
通過測驗驗證
@Test
public void should_check_path_variable() throws Exception {
mockMvc.perform(get("/api/person/6")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest())
.andExpect(content().string("getPersonByID.id: 超過 id 的范圍了"));
}
@Test
public void should_check_request_param_value2() throws Exception {
mockMvc.perform(put("/api/person")
.param("name", "snailclimbsnailclimb")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest())
.andExpect(content().string("getPersonByName.name: 超過 name 的范圍了"));
}
使用 Postman 驗證


驗證 Service 中的方法
我們還可以驗證任何 Spring Bean 的輸入,而不僅僅是 Controller 級別的輸入,通過使用@Validated和@Valid注釋的組合即可實作這一需求!
一般情況下,我們在專案中也更傾向于使用這種方案,
一定一定不要忘記在類上加上 Validated 注解了,這個引數可以告訴 Spring 去校驗方法引數,
@Service
@Validated
public class PersonService {
public void validatePersonRequest(@Valid PersonRequest personRequest) {
// do something
}
}
通過測驗驗證:
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
@Autowired
private PersonService service;
@Test
public void should_throw_exception_when_person_request_is_not_valid() {
try {
PersonRequest personRequest = PersonRequest.builder().sex("Man22")
.classId("82938390").build();
service.validatePersonRequest(personRequest);
} catch (ConstraintViolationException e) {
// 輸出例外資訊
e.getConstraintViolations().forEach(constraintViolation -> System.out.println(constraintViolation.getMessage()));
}
}
}
輸出結果如下:
name 不能為空
sex 值不在可選范圍
Validator 編程方式手動進行引數驗證
某些場景下可能會需要我們手動校驗并獲得校驗結果,
我們通過 Validator 工廠類獲得的 Validator 示例,另外,如果是在 Spring Bean 中的話,還可以通過 @Autowired 直接注入的方式,
@Autowired
Validator validate
具體使用情況如下:
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator()
PersonRequest personRequest = PersonRequest.builder().sex("Man22")
.classId("82938390").build();
Set<ConstraintViolation<PersonRequest>> violations = validator.validate(personRequest);
// 輸出例外資訊
violations.forEach(constraintViolation -> System.out.println(constraintViolation.getMessage()));
}
輸出結果如下:
sex 值不在可選范圍
name 不能為空
自定以 Validator(實用)
如果自帶的校驗注解無法滿足你的需求的話,你還可以自定義實作注解,
案例一:校驗特定欄位的值是否在可選范圍
比如我們現在多了這樣一個需求:PersonRequest 類多了一個 Region 欄位,Region 欄位只能是China、China-Taiwan、China-HongKong這三個中的一個,
第一步,你需要創建一個注解 Region,
@Target({FIELD})
@Retention(RUNTIME)
@Constraint(validatedBy = RegionValidator.class)
@Documented
public @interface Region {
String message() default "Region 值不在可選范圍內";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
第二步,你需要實作 ConstraintValidator介面,并重寫isValid 方法,
public class RegionValidator implements ConstraintValidator<Region, String> {
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
HashSet<Object> regions = new HashSet<>();
regions.add("China");
regions.add("China-Taiwan");
regions.add("China-HongKong");
return regions.contains(value);
}
}
現在你就可以使用這個注解:
@Region
private String region;
通過測驗驗證
PersonRequest personRequest = PersonRequest.builder()
.region("Shanghai").build();
mockMvc.perform(post("/api/person")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(personRequest)))
.andExpect(MockMvcResultMatchers.jsonPath("region").value("Region 值不在可選范圍內"));
使用 Postman 驗證

案例二:校驗電話號碼
校驗我們的電話號碼是否合法,這個可以通過正則運算式來做,相關的正則運算式都可以在網上搜到,你甚至可以搜索到針對特定運營商電話號碼段的正則運算式,
PhoneNumber.java
@Documented
@Constraint(validatedBy = PhoneNumberValidator.class)
@Target({FIELD, PARAMETER})
@Retention(RUNTIME)
public @interface PhoneNumber {
String message() default "Invalid phone number";
Class[] groups() default {};
Class[] payload() default {};
}
PhoneNumberValidator.java
public class PhoneNumberValidator implements ConstraintValidator<PhoneNumber, String> {
@Override
public boolean isValid(String phoneField, ConstraintValidatorContext context) {
if (phoneField == null) {
// can be null
return true;
}
// 大陸手機號碼11位數,匹配格式:前三位固定格式+后8位任意數
// ^ 匹配輸入字串開始的位置
// \d 匹配一個或多個數字,其中 \ 要轉義,所以是 \\d
// $ 匹配輸入字串結尾的位置
String regExp = "^[1]((3[0-9])|(4[5-9])|(5[0-3,5-9])|([6][5,6])|(7[0-9])|(8[0-9])|(9[1,8,9]))\\d{8}$";
return phoneField.matches(regExp);
}
}
搞定,我們現在就可以使用這個注解了,
@PhoneNumber(message = "phoneNumber 格式不正確")
@NotNull(message = "phoneNumber 不能為空")
private String phoneNumber;
通過測驗驗證
PersonRequest personRequest = PersonRequest.builder()
.phoneNumber("1816313815").build();
mockMvc.perform(post("/api/person")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(personRequest)))
.andExpect(MockMvcResultMatchers.jsonPath("phoneNumber").value("phoneNumber 格式不正確"));

使用驗證組
驗證組我們基本是不會用到的,也不太建議在專案中使用,理解起來比較麻煩,寫起來也比較麻煩,簡單了解即可!
當我們對物件操作的不同方法有不同的驗證規則的時候才會用到驗證組,
我寫一個簡單的例子,你們就能看明白了!
1.先創建兩個介面,代表不同的驗證組
public interface AddPersonGroup {
}
public interface DeletePersonGroup {
}
2.使用驗證組
@Data
public class Person {
// 當驗證組為 DeletePersonGroup 的時候 group 欄位不能為空
@NotNull(groups = DeletePersonGroup.class)
// 當驗證組為 AddPersonGroup 的時候 group 欄位需要為空
@Null(groups = AddPersonGroup.class)
private String group;
}
@Service
@Validated
public class PersonService {
@Validated(AddPersonGroup.class)
public void validatePersonGroupForAdd(@Valid Person person) {
// do something
}
@Validated(DeletePersonGroup.class)
public void validatePersonGroupForDelete(@Valid Person person) {
// do something
}
}
通過測驗驗證:
@Test(expected = ConstraintViolationException.class)
public void should_check_person_with_groups() {
Person person = new Person();
person.setGroup("group1");
service.validatePersonGroupForAdd(person);
}
@Test(expected = ConstraintViolationException.class)
public void should_check_person_with_groups2() {
Person person = new Person();
service.validatePersonGroupForDelete(person);
}
驗證組使用下來的體驗就是有點反模式的感覺,讓代碼的可維護性變差了!盡量不要使用!
常用校驗注解總結
JSR303 定義了 Bean Validation(校驗)的標準 validation-api,并沒有提供實作,Hibernate Validation是對這個規范/規范的實作 hibernate-validator,并且增加了 @Email、@Length、@Range 等注解,Spring Validation 底層依賴的就是Hibernate Validation,
JSR 提供的校驗注解:
@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,且長度必須大于 0@Email被注釋的元素必須是電子郵箱地址@Length(min=,max=)被注釋的字串的大小必須在指定的范圍內@NotEmpty被注釋的字串的必須非空@Range(min=,max=,message=)被注釋的元素必須在合適的范圍內
拓展
經常有小伙伴問到:“@NotNull 和 @Column(nullable = false) 兩者有什么區別?”
我這里簡單回答一下:
@NotNull是 JSR 303 Bean 驗證批注,它與資料庫約束本身無關,@Column(nullable = false): 是 JPA 宣告列為非空的方法,
總結來說就是即前者用于驗證,而后者則用于指示資料庫創建表的時候對表的約束,
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/281318.html
標籤:其他
