如何在 Spring/Spring Boot 中做參數校驗?你需要了解的都在這裏! 如何在 Spring/Spring Boot 中做參數校驗?你需要了解的都在這裏!

摘自:https://www.cnblogs.com/javaguide/p/11832752.html

如何在 Spring/Spring Boot 中做參數校驗?你需要了解的都在這裏!

 

本文爲作者原創,如需轉載請在文首著名地址,公衆號轉載請申請開白。

springboot-guide : 適合新手入門以及有經驗的開發人員查閱的 Spring Boot 教程(業餘時間維護中,歡迎一起維護)。

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

本文結合自己在項目中的實際使用經驗,可以說文章介紹的內容很實用,不瞭解的朋友可以學習一下,後面可以立馬實踐到項目上去。

下面我會通過實例程序演示如何在 Java 程序中尤其是 Spring 程序中優雅地的進行參數驗證。

基礎設施搭建

相關依賴

如果開發普通 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-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>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

實體類

下面這個是示例用到的實體類。

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {

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

    @Email(message = "email 格式不正確")
    @NotNull(message = "email 不能爲空")
    private String email;

}

正則表達式說明:

- ^string : 匹配以 string 開頭的字符串
- string$ :匹配以 string 結尾的字符串
- ^string$ :精確匹配 string 字符串
- ((^Man$|^Woman$|^UGM$)) : 值只能在 Man,Woman,UGM 這三個值中選擇

下面這部分校驗註解說明內容參考自:https://www.cnkirito.moe/spring-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=) 被註釋的元素必須在合適的範圍內

驗證Controller的輸入

驗證請求體(RequestBody)

Controller:

我們在需要驗證的參數上加上了@Valid註解,如果驗證失敗,它將拋出MethodArgumentNotValidException。默認情況下,Spring會將此異常轉換爲HTTP Status 400(錯誤請求)。


@RestController
@RequestMapping("/api")
public class PersonController {

    @PostMapping("/person")
    public ResponseEntity<Person> getPerson(@RequestBody @Valid Person person) {
        return ResponseEntity.ok().body(person);
    }
}

ExceptionHandler:

自定義異常處理器可以幫助我們捕獲異常,並進行一些簡單的處理。如果對於下面的處理異常的代碼不太理解的話,可以查看這篇文章 《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 這種工具來驗證。

我們試一下所有參數輸入正確的情況。

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class PersonControllerTest {
    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private ObjectMapper objectMapper;

    @Test
    public void should_get_person_correctly() throws Exception {
        Person person = new Person();
        person.setName("SnailClimb");
        person.setSex("Man");
        person.setClassId("82938390");
        person.setEmail("[email protected]");

        mockMvc.perform(post("/api/person")
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .content(objectMapper.writeValueAsString(person)))
                .andExpect(MockMvcResultMatchers.jsonPath("name").value("SnailClimb"))
                .andExpect(MockMvcResultMatchers.jsonPath("classId").value("82938390"))
                .andExpect(MockMvcResultMatchers.jsonPath("sex").value("Man"))
                .andExpect(MockMvcResultMatchers.jsonPath("email").value("[email protected]"));
    }
}

驗證出現參數不合法的情況拋出異常並且可以正確被捕獲。

 @Test
    public void should_check_person_value() throws Exception {
        Person person = new Person();
        person.setSex("Man22");
        person.setClassId("82938390");
        person.setEmail("SnailClimb");

        mockMvc.perform(post("/api/person")
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .content(objectMapper.writeValueAsString(person)))
                .andExpect(MockMvcResultMatchers.jsonPath("sex").value("sex 值不在可選範圍"))
                .andExpect(MockMvcResultMatchers.jsonPath("name").value("name 不能爲空"))
                .andExpect(MockMvcResultMatchers.jsonPath("email").value("email 格式不正確"));
    }

使用 Postman 驗證結果如下:

Postman 驗證結果

驗證請求參數(Path Variables 和 Request Parameters)

Controller:

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

@RestController
@RequestMapping("/api")
@Validated
public class PersonController {

    @GetMapping("/person/{id}")
    public ResponseEntity<Integer> getPersonByID(@Valid @PathVariable("id") @Max(value = 5,message = "超過 id 的範圍了") Integer id) {
        return ResponseEntity.ok().body(id);
    }

    @PutMapping("/person")
    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_param_value() throws Exception {

        mockMvc.perform(get("/api/person/6")
                .contentType(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(status().isBadRequest())
                .andExpect(content().string("getPersonByID.id: 超過 id 的範圍了"));
    }

    @Test
    public void should_check_param_value2() throws Exception {

        mockMvc.perform(put("/api/person")
                .param("name","snailclimbsnailclimb")
                .contentType(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(status().isBadRequest())
                .andExpect(content().string("getPersonByName.name: 超過 name 的範圍了"));
    }

驗證 Service 中的方法

我們還可以驗證任何Spring組件的輸入,而不是驗證控制器級別的輸入,我們可以使用@Validated@Valid註釋的組合來實現這一需求。

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

@Service
@Validated
public class PersonService {

    public void validatePerson(@Valid Person person){
        // do something
    }
}

通過測試驗證:

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class PersonServiceTest {
    @Autowired
    private PersonService service;

    @Test(expected = ConstraintViolationException.class)
    public void should_throw_exception_when_person_is_not_valid() {
        Person person = new Person();
        person.setSex("Man22");
        person.setClassId("82938390");
        person.setEmail("SnailClimb");
        service.validatePerson(person);
    }

}

Validator 編程方式手動進行參數驗證

某些場景下可能會需要我們手動校驗並獲得校驗結果。

    @Test
    public void check_person_manually() {

        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        Person person = new Person();
        person.setSex("Man22");
        person.setClassId("82938390");
        person.setEmail("SnailClimb");
        Set<ConstraintViolation<Person>> violations = validator.validate(person);
        //output:
        //email 格式不正確
        //name 不能爲空
        //sex 值不在可選範圍
        for (ConstraintViolation<Person> constraintViolation : violations) {
            System.out.println(constraintViolation.getMessage());
        }
    }

上面我們是通過 Validator 工廠類獲得的 Validator 示例,當然你也可以通過 @Autowired 直接注入的方式。但是在非 Spring Component 類中使用這種方式的話,只能通過工廠類來獲得 Validator

@Autowired
Validator validate

自定以 Validator(實用)

如果自帶的校驗註解無法滿足你的需求的話,你還可以自定義實現註解。

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

比如我們現在多了這樣一個需求:Person類多了一個 region 字段,region 字段只能是ChinaChina-TaiwanChina-HongKong這三個中的一個。

第一步你需要創建一個註解:

@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 方法:

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.HashSet;

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;

案例二:校驗電話號碼

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

PhoneNumber.java

import javax.validation.Constraint;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@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

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class PhoneNumberValidator implements ConstraintValidator<PhoneNumber,String> {

    @Override
    public boolean isValid(String phoneField, ConstraintValidatorContext context) {
        if (phoneField == null) {
            // can be null
            return true;
        }
        return phoneField.matches("^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|70)\\d{8}$") && phoneField.length() > 8 && phoneField.length() < 14;
    }
}

搞定,我們現在就可以使用這個註解了。

@PhoneNumber(message = "phoneNumber 格式不正確")
@NotNull(message = "phoneNumber 不能爲空")
private String phoneNumber;

使用驗證組

某些場景下我們需要使用到驗證組,這樣說可能不太清楚,說簡單點就是對對象操作的不同方法有不同的驗證規則,示例如下(這個就我目前經歷的項目來說使用的比較少,因爲本身這個在代碼層面理解起來是比較麻煩的,然後寫起來也比較麻煩)。

先創建兩個接口:

public interface AddPersonGroup {
}
public interface DeletePersonGroup {
}

我們可以這樣去使用驗證組

@NotNull(groups = DeletePersonGroup.class)
@Null(groups = AddPersonGroup.class)
private String group;
@Service
@Validated
public class PersonService {

    public void validatePerson(@Valid Person person) {
        // do something
    }

    @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.setSex("Man22");
        person.setClassId("82938390");
        person.setEmail("SnailClimb");
        person.setGroup("group1");
        service.validatePersonGroupForAdd(person);
    }

    @Test(expected = ConstraintViolationException.class)
    public void should_check_person_with_groups2() {
        Person person = new Person();
        person.setSex("Man22");
        person.setClassId("82938390");
        person.setEmail("SnailClimb");
        service.validatePersonGroupForDelete(person);
    }

使用驗證組這種方式的時候一定要小心,這是一種反模式,還會造成代碼邏輯性變差。

代碼地址:https://github.com/Snailclimb/springboot-guide/tree/master/source-code/advanced/bean-validation-demo

@NotNull vs @Column(nullable = false)(重要)

在使用 JPA 操作數據的時候會經常碰到 @Column(nullable = false) 這種類型的約束,那麼它和 @NotNull 有何區別呢?搞清楚這個還是很重要的!

  • @NotNull是 JSR 303 Bean驗證批註,它與數據庫約束本身無關。
  • @Column(nullable = false) : 是JPA聲明列爲非空的方法。

總結來說就是即前者用於驗證,而後者則用於指示數據庫創建表的時候對錶的約束。

TODO

  • [ ] 原理分析

參考

  • https://reflectoring.io/bean-validation-with-spring-boot/
  • https://www.cnkirito.moe/spring-validation//

開源項目推薦

作者的其他開源項目推薦:

  1. JavaGuide:【Java學習+面試指南】 一份涵蓋大部分Java程序員所需要掌握的核心知識。
  2. springboot-guide : 適合新手入門以及有經驗的開發人員查閱的 Spring Boot 教程(業餘時間維護中,歡迎一起維護)。
  3. programmer-advancement : 我覺得技術人員應該有的一些好習慣!
  4. spring-security-jwt-guide :從零入門 !Spring Security With JWT(含權限驗證)後端部分代碼。
 
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章