Spring/Spring Boot 中優(yōu)雅地做參數(shù)校驗(yàn)拒絕 if/else 參數(shù)校驗(yàn)
數(shù)據(jù)的校驗(yàn)的重要性就不用說(shuō)了,即使在前端對(duì)數(shù)據(jù)進(jìn)行校驗(yàn)的情況下,我們還是要對(duì)傳入后端的數(shù)據(jù)再進(jìn)行一遍校驗(yàn),避免用戶繞過(guò)瀏覽器直接通過(guò)一些 HTTP 工具直接向后端請(qǐng)求一些違法數(shù)據(jù)。
最普通的做法就像下面這樣。我們通過(guò) if/else
語(yǔ)句對(duì)請(qǐng)求的每一個(gè)參數(shù)一一校驗(yàn)。
@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); } }
這樣的代碼,小伙伴們?cè)谌粘i_(kāi)發(fā)中一定不少見(jiàn),很多開(kāi)源項(xiàng)目都是這樣對(duì)請(qǐng)求入?yún)⒆鲂r?yàn)的。
但是,不太建議這樣來(lái)寫(xiě),這樣的代碼明顯違背了 單一職責(zé)原則。大量的非業(yè)務(wù)代碼混雜在業(yè)務(wù)代碼中,非常難以維護(hù),還會(huì)導(dǎo)致業(yè)務(wù)層代碼冗雜!
實(shí)際上,我們是可以通過(guò)一些簡(jiǎn)單的手段對(duì)上面的代碼進(jìn)行改進(jìn)的!這也是本文主要要介紹的內(nèi)容!
廢話不多說(shuō)!下面我會(huì)結(jié)合自己在項(xiàng)目中的實(shí)際使用經(jīng)驗(yàn),通過(guò)實(shí)例程序演示如何在 SpringBoot 程序中優(yōu)雅地的進(jìn)行參數(shù)驗(yàn)證(普通的 Java 程序同樣適用)。
不了解的朋友一定要好好看一下,學(xué)完馬上就可以實(shí)踐到項(xiàng)目上去。
并且,本文示例項(xiàng)目使用的是目前最新的 Spring Boot 版本 2.4.5!(截止到 2021-04-21)
示例項(xiàng)目源代碼地址:https://github.com/CodingDocs/springboot-guide/tree/master/source-code/bean-validation-demo 。
添加相關(guān)依賴
如果開(kāi)發(fā)普通 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>
不過(guò),相信大家都是使用的 Spring Boot 框架來(lái)做開(kāi)發(fā)。
基于 Spring Boot 的話,就比較簡(jiǎn)單了,只需要給項(xiàng)目添加上 spring-boot-starter-web
依賴就夠了,它的子依賴包含了我們所需要的東西。另外,我們的示例項(xiàng)目中還使用到了 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
已經(jīng)不包括在了 spring-boot-starter-web
中,需要我們手動(dòng)加上!
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
驗(yàn)證 Controller 的輸入
驗(yàn)證請(qǐng)求體
驗(yàn)證請(qǐng)求體即使驗(yàn)證被 @RequestBody
注解標(biāo)記的方法參數(shù)。
PersonController
我們?cè)谛枰?yàn)證的參數(shù)上加上了@Valid
注解,如果驗(yàn)證失敗,它將拋出MethodArgumentNotValidException
。默認(rèn)情況下,Spring 會(huì)將此異常轉(zhuǎn)換為 HTTP Status 400(錯(cuò)誤請(qǐng)求)。
@RestController @RequestMapping("/api/person") @Validated public class PersonController { @PostMapping public ResponseEntity<PersonRequest> save(@RequestBody @Valid PersonRequest personRequest) { return ResponseEntity.ok().body(personRequest); } }
PersonRequest
我們使用校驗(yàn)注解對(duì)請(qǐng)求的參數(shù)進(jìn)行校驗(yàn)!
@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; }
正則表達(dá)式說(shuō)明:
^string
: 匹配以 string 開(kāi)頭的字符串string$
:匹配以 string 結(jié)尾的字符串^string$
:精確匹配 string 字符串(^Man$|^Woman$|^UGM$)
: 值只能在 Man,Woman,UGM 這三個(gè)值中選擇
GlobalExceptionHandler
自定義異常處理器可以幫助我們捕獲異常,并進(jìn)行一些簡(jiǎn)單的處理。如果對(duì)于下面的處理異常的代碼不太理解的話,可以查看這篇文章 《SpringBoot 處理異常的幾種常見(jiàn)姿勢(shì)》。
@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); } }
通過(guò)測(cè)試驗(yàn)證
下面我通過(guò) MockMvc
模擬請(qǐng)求 Controller
的方式來(lái)驗(yàn)證是否生效。當(dāng)然了,你也可以通過(guò) Postman
這種工具來(lái)驗(yàn)證。
@SpringBootTest @AutoConfigureMockMvc public class PersonControllerTest { @Autowired private MockMvc mockMvc; @Autowired private ObjectMapper objectMapper; /** * 驗(yàn)證出現(xiàn)參數(shù)不合法的情況拋出異常并且可以正確被捕獲 */ @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
驗(yàn)證
驗(yàn)證請(qǐng)求參數(shù)
驗(yàn)證請(qǐng)求參數(shù)(Path Variables 和 Request Parameters)即是驗(yàn)證被 @PathVariable
以及 @RequestParam
標(biāo)記的方法參數(shù)。
PersonController
一定一定不要忘記在類(lèi)上加上 Validated
注解了,這個(gè)參數(shù)可以告訴 Spring 去校驗(yàn)方法參數(shù)。
@RestController @RequestMapping("/api/persons") @Validated public class PersonController { @GetMapping("/{id}") public ResponseEntity<Integer> getPersonByID(@Valid @PathVariable("id") @Max(value = 5, message = "超過(guò) id 的范圍了") Integer id) { return ResponseEntity.ok().body(id); } @PutMapping public ResponseEntity<String> getPersonByName(@Valid @RequestParam("name") @Size(max = 6, message = "超過(guò) 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()); }
通過(guò)測(cè)試驗(yàn)證
@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: 超過(guò) 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: 超過(guò) name 的范圍了")); }
使用 Postman
驗(yàn)證
驗(yàn)證 Service 中的方法
我們還可以驗(yàn)證任何 Spring Bean 的輸入,而不僅僅是 Controller
級(jí)別的輸入。通過(guò)使用@Validated
和@Valid
注釋的組合即可實(shí)現(xiàn)這一需求!
一般情況下,我們?cè)陧?xiàng)目中也更傾向于使用這種方案。
一定一定不要忘記在類(lèi)上加上 Validated
注解了,這個(gè)參數(shù)可以告訴 Spring 去校驗(yàn)方法參數(shù)。
@Service @Validated public class PersonService { public void validatePersonRequest(@Valid PersonRequest personRequest) { // do something } }
通過(guò)測(cè)試驗(yàn)證:
@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())); } } }
輸出結(jié)果如下:
name 不能為空
sex 值不在可選范圍
Validator 編程方式手動(dòng)進(jìn)行參數(shù)驗(yàn)證
某些場(chǎng)景下可能會(huì)需要我們手動(dòng)校驗(yàn)并獲得校驗(yàn)結(jié)果。
我們通過(guò) Validator
工廠類(lèi)獲得的 Validator
示例。另外,如果是在 Spring Bean 中的話,還可以通過(guò) @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())); }
輸出結(jié)果如下:
sex 值不在可選范圍
name 不能為空
自定以 Validator(實(shí)用)
如果自帶的校驗(yàn)注解無(wú)法滿足你的需求的話,你還可以自定義實(shí)現(xiàn)注解。
案例一:校驗(yàn)特定字段的值是否在可選范圍
比如我們現(xiàn)在多了這樣一個(gè)需求:PersonRequest
類(lèi)多了一個(gè) Region
字段,Region
字段只能是China
、China-Taiwan
、China-HongKong
這三個(gè)中的一個(gè)。
第一步,你需要?jiǎng)?chuàng)建一個(gè)注解 Region
。
@Target({FIELD}) @Retention(RUNTIME) @Constraint(validatedBy = RegionValidator.class) @Documented public @interface Region { String message() default "Region 值不在可選范圍內(nèi)"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
第二步,你需要實(shí)現(xiàn) ConstraintValidator
接口,并重寫(xiě)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); } }
現(xiàn)在你就可以使用這個(gè)注解:
@Region private String region;
通過(guò)測(cè)試驗(yàn)證
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 值不在可選范圍內(nèi)"));
使用 Postman
驗(yàn)證
案例二:校驗(yàn)電話號(hào)碼
校驗(yàn)我們的電話號(hào)碼是否合法,這個(gè)可以通過(guò)正則表達(dá)式來(lái)做,相關(guān)的正則表達(dá)式都可以在網(wǎng)上搜到,你甚至可以搜索到針對(duì)特定運(yùn)營(yíng)商電話號(hào)碼段的正則表達(dá)式。
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; } // 大陸手機(jī)號(hào)碼11位數(shù),匹配格式:前三位固定格式+后8位任意數(shù) // ^ 匹配輸入字符串開(kāi)始的位置 // \d 匹配一個(gè)或多個(gè)數(shù)字,其中 \ 要轉(zhuǎn)義,所以是 \\d // $ 匹配輸入字符串結(jié)尾的位置 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); } }
搞定,我們現(xiàn)在就可以使用這個(gè)注解了。
@PhoneNumber(message = "phoneNumber 格式不正確") @NotNull(message = "phoneNumber 不能為空") private String phoneNumber;
通過(guò)測(cè)試驗(yàn)證
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 格式不正確"));
使用驗(yàn)證組
驗(yàn)證組我們基本是不會(huì)用到的,也不太建議在項(xiàng)目中使用,理解起來(lái)比較麻煩,寫(xiě)起來(lái)也比較麻煩。簡(jiǎn)單了解即可!
當(dāng)我們對(duì)對(duì)象操作的不同方法有不同的驗(yàn)證規(guī)則的時(shí)候才會(huì)用到驗(yàn)證組。
我寫(xiě)一個(gè)簡(jiǎn)單的例子,你們就能看明白了!
1.先創(chuàng)建兩個(gè)接口,代表不同的驗(yàn)證組
public interface AddPersonGroup { } public interface DeletePersonGroup { }
2.使用驗(yàn)證組
@Data public class Person { // 當(dāng)驗(yàn)證組為 DeletePersonGroup 的時(shí)候 group 字段不能為空 @NotNull(groups = DeletePersonGroup.class) // 當(dāng)驗(yàn)證組為 AddPersonGroup 的時(shí)候 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 } }
通過(guò)測(cè)試驗(yàn)證:
@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); }
驗(yàn)證組使用下來(lái)的體驗(yàn)就是有點(diǎn)反模式的感覺(jué),讓代碼的可維護(hù)性變差了!盡量不要使用!
常用校驗(yàn)注解總結(jié)
JSR303
定義了 Bean Validation
(校驗(yàn))的標(biāo)準(zhǔn) validation-api
,并沒(méi)有提供實(shí)現(xiàn)。Hibernate Validation
是對(duì)這個(gè)規(guī)范/規(guī)范的實(shí)現(xiàn) hibernate-validator
,并且增加了 @Email
、@Length
、@Range
等注解。Spring Validation
底層依賴的就是Hibernate Validation
。
JSR 提供的校驗(yàn)注解:
@Null
被注釋的元素必須為 null@NotNull
被注釋的元素必須不為 null@AssertTrue
被注釋的元素必須為 true@AssertFalse
被注釋的元素必須為 false@Min(value)
被注釋的元素必須是一個(gè)數(shù)字,其值必須大于等于指定的最小值@Max(value)
被注釋的元素必須是一個(gè)數(shù)字,其值必須小于等于指定的最大值@DecimalMin(value)
被注釋的元素必須是一個(gè)數(shù)字,其值必須大于等于指定的最小值@DecimalMax(value)
被注釋的元素必須是一個(gè)數(shù)字,其值必須小于等于指定的最大值@Size(max=, min=)
被注釋的元素的大小必須在指定的范圍內(nèi)@Digits (integer, fraction)
被注釋的元素必須是一個(gè)數(shù)字,其值必須在可接受的范圍內(nèi)@Past
被注釋的元素必須是一個(gè)過(guò)去的日期@Future
被注釋的元素必須是一個(gè)將來(lái)的日期@Pattern(regex=,flag=)
被注釋的元素必須符合指定的正則表達(dá)式
Hibernate Validator 提供的校驗(yàn)注解:
@NotBlank(message =)
驗(yàn)證字符串非 null,且長(zhǎng)度必須大于 0@Email
被注釋的元素必須是電子郵箱地址@Length(min=,max=)
被注釋的字符串的大小必須在指定的范圍內(nèi)@NotEmpty
被注釋的字符串的必須非空@Range(min=,max=,message=)
被注釋的元素必須在合適的范圍內(nèi)
拓展
經(jīng)常有小伙伴問(wèn)到:“@NotNull
和 @Column(nullable = false)
兩者有什么區(qū)別?”
我這里簡(jiǎn)單回答一下:
@NotNull
是 JSR 303 Bean 驗(yàn)證批注,它與數(shù)據(jù)庫(kù)約束本身無(wú)關(guān)。@Column(nullable = false)
: 是 JPA 聲明列為非空的方法。
總結(jié)來(lái)說(shuō)就是即前者用于驗(yàn)證,而后者則用于指示數(shù)據(jù)庫(kù)創(chuàng)建表的時(shí)候?qū)Ρ淼募s束。
到此這篇關(guān)于Spring/Spring Boot 中優(yōu)雅地做參數(shù)校驗(yàn)拒絕 if/else 參數(shù)校驗(yàn)的文章就介紹到這了,更多相關(guān)Spring/Spring Boot 參數(shù)校驗(yàn)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
一文帶你搞懂Java中方法重寫(xiě)與方法重載的區(qū)別
這篇文章主要介紹了Java中方法重寫(xiě)與方法重載有哪些區(qū)別,文中有詳細(xì)的代碼示例,對(duì)大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2023-05-05Java中Stringbuild,Date和Calendar類(lèi)的用法詳解
這篇文章主要為大家詳細(xì)介紹了Java中Stringbuild、Date和Calendar類(lèi)的用法,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起了解一下2023-04-04SpringBoot?整合?ShardingSphere4.1.1實(shí)現(xiàn)分庫(kù)分表功能
ShardingSphere是一套開(kāi)源的分布式數(shù)據(jù)庫(kù)中間件解決方案組成的生態(tài)圈,它由Sharding-JDBC、Sharding-Proxy和Sharding-Sidecar(計(jì)劃中)這3款相互獨(dú)立的產(chǎn)品組成,本文給大家介紹SpringBoot?整合?ShardingSphere4.1.1實(shí)現(xiàn)分庫(kù)分表,感興趣的朋友一起看看吧2023-12-12java分類(lèi)樹(shù),我從2s優(yōu)化到0.1s
這篇文章主要介紹了java分類(lèi)樹(shù),我從2s優(yōu)化到0.1s的相關(guān)資料,需要的朋友可以參考下2023-05-05UrlDecoder和UrlEncoder使用詳解_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要為大家詳細(xì)介紹了UrlDecoder和UrlEncoder使用方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-07-07- Spring事務(wù)的本質(zhì)就是對(duì)數(shù)據(jù)庫(kù)事務(wù)的支持,沒(méi)有數(shù)據(jù)庫(kù)事務(wù),Spring是無(wú)法提供事務(wù)功能的。Spring只提供統(tǒng)一的事務(wù)管理接口,具體實(shí)現(xiàn)都是由數(shù)據(jù)庫(kù)自己實(shí)現(xiàn)的,Spring會(huì)在事務(wù)開(kāi)始時(shí),根據(jù)當(dāng)前設(shè)置的隔離級(jí)別,調(diào)整數(shù)據(jù)庫(kù)的隔離級(jí)別,由此保持一致2022-04-04