欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring/Spring Boot 中優(yōu)雅地做參數(shù)校驗拒絕 if/else 參數(shù)校驗

 更新時間:2021年04月30日 10:56:50   作者:JavaGuide  
這篇文章主要介紹了Spring/Spring Boot 中優(yōu)雅地做參數(shù)校驗拒絕 if/else 參數(shù)校驗,本文使用最新的 Spring Boot 版本 2.4.5,通過實例代碼給大家介紹的非常詳細,需要的朋友可以參考下

數(shù)據(jù)的校驗的重要性就不用說了,即使在前端對數(shù)據(jù)進行校驗的情況下,我們還是要對傳入后端的數(shù)據(jù)再進行一遍校驗,避免用戶繞過瀏覽器直接通過一些 HTTP 工具直接向后端請求一些違法數(shù)據(jù)。

最普通的做法就像下面這樣。我們通過 if/else 語句對請求的每一個參數(shù)一一校驗。

@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);
    }
}

這樣的代碼,小伙伴們在日常開發(fā)中一定不少見,很多開源項目都是這樣對請求入?yún)⒆鲂r灥摹?/p>

但是,不太建議這樣來寫,這樣的代碼明顯違背了 單一職責原則。大量的非業(yè)務(wù)代碼混雜在業(yè)務(wù)代碼中,非常難以維護,還會導致業(yè)務(wù)層代碼冗雜!

實際上,我們是可以通過一些簡單的手段對上面的代碼進行改進的!這也是本文主要要介紹的內(nèi)容!

廢話不多說!下面我會結(jié)合自己在項目中的實際使用經(jīng)驗,通過實例程序演示如何在 SpringBoot 程序中優(yōu)雅地的進行參數(shù)驗證(普通的 Java 程序同樣適用)。

不了解的朋友一定要好好看一下,學完馬上就可以實踐到項目上去。

并且,本文示例項目使用的是目前最新的 Spring Boot 版本 2.4.5!(截止到 2021-04-21)

示例項目源代碼地址:https://github.com/CodingDocs/springboot-guide/tree/master/source-code/bean-validation-demo 。

添加相關(guān)依賴

如果開發(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>

不過,相信大家都是使用的 Spring Boot 框架來做開發(fā)。

基于 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 已經(jīng)不包括在了 spring-boot-starter-web 中,需要我們手動加上!

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

驗證 Controller 的輸入

驗證請求體

驗證請求體即使驗證被 @RequestBody 注解標記的方法參數(shù)。

PersonController

我們在需要驗證的參數(shù)上加上了@Valid注解,如果驗證失敗,它將拋出MethodArgumentNotValidException。默認情況下,Spring 會將此異常轉(zhuǎn)換為 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

我們使用校驗注解對請求的參數(shù)進行校驗!

@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 結(jié)尾的字符串
  • ^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;
    /**
     * 驗證出現(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 驗證

驗證請求參數(shù)

驗證請求參數(shù)(Path Variables 和 Request Parameters)即是驗證被 @PathVariable 以及 @RequestParam 標記的方法參數(shù)。

PersonController

一定一定不要忘記在類上加上 Validated 注解了,這個參數(shù)可以告訴 Spring 去校驗方法參數(shù)。

@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注釋的組合即可實現(xiàn)這一需求!

一般情況下,我們在項目中也更傾向于使用這種方案。

一定一定不要忘記在類上加上 Validated 注解了,這個參數(shù)可以告訴 Spring 去校驗方法參數(shù)。

@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()));
        }
    }
}

輸出結(jié)果如下:

name 不能為空
sex 值不在可選范圍

Validator 編程方式手動進行參數(shù)驗證

某些場景下可能會需要我們手動校驗并獲得校驗結(jié)果。

我們通過 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()));
}

輸出結(jié)果如下:

sex 值不在可選范圍
name 不能為空

自定以 Validator(實用)

如果自帶的校驗注解無法滿足你的需求的話,你還可以自定義實現(xiàn)注解。

案例一:校驗特定字段的值是否在可選范圍

比如我們現(xiàn)在多了這樣一個需求:PersonRequest 類多了一個 Region 字段,Region 字段只能是China、China-Taiwan、China-HongKong這三個中的一個。

第一步,你需要創(chuàng)建一個注解 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 {};
}

第二步,你需要實現(xiàn) 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);
    }
}

現(xiàn)在你就可以使用這個注解:

@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 值不在可選范圍內(nèi)"));

使用 Postman 驗證

案例二:校驗電話號碼

校驗我們的電話號碼是否合法,這個可以通過正則表達式來做,相關(guān)的正則表達式都可以在網(wǎng)上搜到,你甚至可以搜索到針對特定運營商電話號碼段的正則表達式。

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位數(shù),匹配格式:前三位固定格式+后8位任意數(shù)
        // ^ 匹配輸入字符串開始的位置
        // \d 匹配一個或多個數(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)在就可以使用這個注解了。

@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 格式不正確"));

使用驗證組

驗證組我們基本是不會用到的,也不太建議在項目中使用,理解起來比較麻煩,寫起來也比較麻煩。簡單了解即可!

當我們對對象操作的不同方法有不同的驗證規(guī)則的時候才會用到驗證組。

我寫一個簡單的例子,你們就能看明白了!

1.先創(chuàng)建兩個接口,代表不同的驗證組

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);
  }

驗證組使用下來的體驗就是有點反模式的感覺,讓代碼的可維護性變差了!盡量不要使用!

常用校驗注解總結(jié)

JSR303 定義了 Bean Validation(校驗)的標準 validation-api,并沒有提供實現(xiàn)。Hibernate Validation是對這個規(guī)范/規(guī)范的實現(xiàn) hibernate-validator,并且增加了 @Email@Length、@Range 等注解。Spring Validation 底層依賴的就是Hibernate Validation。

JSR 提供的校驗注解:

  • @Null 被注釋的元素必須為 null
  • @NotNull 被注釋的元素必須不為 null
  • @AssertTrue 被注釋的元素必須為 true
  • @AssertFalse 被注釋的元素必須為 false
  • @Min(value) 被注釋的元素必須是一個數(shù)字,其值必須大于等于指定的最小值
  • @Max(value) 被注釋的元素必須是一個數(shù)字,其值必須小于等于指定的最大值
  • @DecimalMin(value) 被注釋的元素必須是一個數(shù)字,其值必須大于等于指定的最小值
  • @DecimalMax(value) 被注釋的元素必須是一個數(shù)字,其值必須小于等于指定的最大值
  • @Size(max=, min=) 被注釋的元素的大小必須在指定的范圍內(nèi)
  • @Digits (integer, fraction) 被注釋的元素必須是一個數(shù)字,其值必須在可接受的范圍內(nèi)
  • @Past 被注釋的元素必須是一個過去的日期
  • @Future 被注釋的元素必須是一個將來的日期
  • @Pattern(regex=,flag=) 被注釋的元素必須符合指定的正則表達式

Hibernate Validator 提供的校驗注解:

  • @NotBlank(message =) 驗證字符串非 null,且長度必須大于 0
  • @Email 被注釋的元素必須是電子郵箱地址
  • @Length(min=,max=) 被注釋的字符串的大小必須在指定的范圍內(nèi)
  • @NotEmpty 被注釋的字符串的必須非空
  • @Range(min=,max=,message=) 被注釋的元素必須在合適的范圍內(nèi)

拓展

經(jīng)常有小伙伴問到:“@NotNull@Column(nullable = false) 兩者有什么區(qū)別?”

我這里簡單回答一下:

  • @NotNull是 JSR 303 Bean 驗證批注,它與數(shù)據(jù)庫約束本身無關(guān)。
  • @Column(nullable = false) : 是 JPA 聲明列為非空的方法。

總結(jié)來說就是即前者用于驗證,而后者則用于指示數(shù)據(jù)庫創(chuàng)建表的時候?qū)Ρ淼募s束。

到此這篇關(guān)于Spring/Spring Boot 中優(yōu)雅地做參數(shù)校驗拒絕 if/else 參數(shù)校驗的文章就介紹到這了,更多相關(guān)Spring/Spring Boot 參數(shù)校驗內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 一文帶你搞懂Java中方法重寫與方法重載的區(qū)別

    一文帶你搞懂Java中方法重寫與方法重載的區(qū)別

    這篇文章主要介紹了Java中方法重寫與方法重載有哪些區(qū)別,文中有詳細的代碼示例,對大家的學習或工作有一定的幫助,需要的朋友可以參考下
    2023-05-05
  • Java中Stringbuild,Date和Calendar類的用法詳解

    Java中Stringbuild,Date和Calendar類的用法詳解

    這篇文章主要為大家詳細介紹了Java中Stringbuild、Date和Calendar類的用法,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起了解一下
    2023-04-04
  • Java中i++的一些問題總結(jié)

    Java中i++的一些問題總結(jié)

    這篇文章主要給大家介紹了關(guān)于Java中i++的一些問題,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-12-12
  • 深入理解Java設(shè)計模式之觀察者模式

    深入理解Java設(shè)計模式之觀察者模式

    這篇文章主要介紹了JAVA設(shè)計模式之觀察者模式的的相關(guān)資料,文中示例代碼非常詳細,供大家參考和學習,感興趣的朋友可以了解
    2021-11-11
  • 高內(nèi)聚低耦合法則實例解析

    高內(nèi)聚低耦合法則實例解析

    這篇文章主要介紹了高內(nèi)聚低耦合法則實例代碼解析,具有一定借鑒價值,需要的朋友可以參考下。
    2017-12-12
  • JVM的垃圾回收算法一起來看看

    JVM的垃圾回收算法一起來看看

    這篇文章主要為大家詳細介紹了JVM的垃圾回收算法,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2022-03-03
  • SpringBoot?整合?ShardingSphere4.1.1實現(xiàn)分庫分表功能

    SpringBoot?整合?ShardingSphere4.1.1實現(xiàn)分庫分表功能

    ShardingSphere是一套開源的分布式數(shù)據(jù)庫中間件解決方案組成的生態(tài)圈,它由Sharding-JDBC、Sharding-Proxy和Sharding-Sidecar(計劃中)這3款相互獨立的產(chǎn)品組成,本文給大家介紹SpringBoot?整合?ShardingSphere4.1.1實現(xiàn)分庫分表,感興趣的朋友一起看看吧
    2023-12-12
  • java分類樹,我從2s優(yōu)化到0.1s

    java分類樹,我從2s優(yōu)化到0.1s

    這篇文章主要介紹了java分類樹,我從2s優(yōu)化到0.1s的相關(guān)資料,需要的朋友可以參考下
    2023-05-05
  • UrlDecoder和UrlEncoder使用詳解_動力節(jié)點Java學院整理

    UrlDecoder和UrlEncoder使用詳解_動力節(jié)點Java學院整理

    這篇文章主要為大家詳細介紹了UrlDecoder和UrlEncoder使用方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-07-07
  • Spring詳細解讀事務(wù)管理

    Spring詳細解讀事務(wù)管理

    Spring事務(wù)的本質(zhì)就是對數(shù)據(jù)庫事務(wù)的支持,沒有數(shù)據(jù)庫事務(wù),Spring是無法提供事務(wù)功能的。Spring只提供統(tǒng)一的事務(wù)管理接口,具體實現(xiàn)都是由數(shù)據(jù)庫自己實現(xiàn)的,Spring會在事務(wù)開始時,根據(jù)當前設(shè)置的隔離級別,調(diào)整數(shù)據(jù)庫的隔離級別,由此保持一致
    2022-04-04

最新評論