本文已經收錄進 SpringBootGuide (SpringBoot2.0+從入門到實戰!)前端
- Github地址:https://github.com/CodingDocs/springboot-guide
- 碼雲地址:https://gitee.com/SnailClimb/springboot-guide(Github沒法訪問或者訪問速度比較慢的小夥伴能夠看碼雲上的對應內容)
數據的校驗的重要性就不用說了,即便在前端對數據進行校驗的狀況下,咱們仍是要對傳入後端的數據再進行一遍校驗,避免用戶繞過瀏覽器直接經過一些 HTTP 工具直接向後端請求一些違法數據。java
最普通的作法就像下面這樣。咱們經過 if/else
語句對請求的每個參數一一校驗。git
@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); } }
這樣的代碼,小夥伴們在平常開發中必定很多見,不少開源項目都是這樣對請求入參作校驗的。github
可是,不太建議這樣來寫,這樣的代碼明顯違背了 單一職責原則。大量的非業務代碼混雜在業務代碼中,很是難以維護,還會致使業務層代碼冗雜!web
實際上,咱們是能夠經過一些簡單的手段對上面的代碼進行改進的!這也是本文主要要介紹的內容!正則表達式
廢話很少說!下面我會結合本身在項目中的實際使用經驗,經過實例程序演示如何在 SpringBoot 程序中優雅地的進行參數驗證(普通的 Java 程序一樣適用)。spring
不瞭解的朋友必定要好好看一下,學完立刻就能夠實踐到項目上去。數據庫
而且,本文示例項目使用的是目前最新的 Spring Boot 版本 2.4.5!(截止到 2021-04-21)編程
示例項目源代碼地址:https://github.com/CodingDocs/springboot-guide/tree/master/source-code/bean-validation-demo 。json
若是開發普通 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>
驗證請求體即便驗證被 @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
驗證
咱們還能夠驗證任何 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
示例。另外,若是是在 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 不能爲空
若是自帶的校驗註解沒法知足你的需求的話,你還能夠自定義實現註解。
好比咱們如今多了這樣一個需求: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 聲明列爲非空的方法。總結來講就是即前者用於驗證,然後者則用於指示數據庫建立表的時候對錶的約束。
我是 Guide哥,擁抱開源,喜歡烹飪。Github 接近 10w 點讚的開源項目 JavaGuide 的做者。將來幾年,但願持續完善 JavaGuide,爭取可以幫助更多學習 Java 的小夥伴!共勉!凎!點擊查看個人2020年工做彙報!
原創不易,歡迎點贊分享。我們下期再會!