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

原創: SnailClimb [JavaGuide](javascript:void(0);)

本文已經收錄自 JavaGuide 開源的 springboot-guide : https://github.com/Snailclimb/springboot-guide (SpringBoot 核心知識點總結。基于 Spring Boot 2.19+),歡迎 Star!

image

圖源:unsplash

數據的校驗的重要性就不用說了,即使在前端對數據進行校驗的情況下,我們還是要對傳入后端的數據再進行一遍校驗,避免用戶繞過瀏覽器直接通過一些 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("Snailclimb@qq.com"); 
       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("Snailclimb@qq.com")); 
   }
}

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

 @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 驗證結果如下:

image

<figcaption style="margin: 5px 0px 0px; padding: 0px; max-width: 100%; box-sizing: border-box !important; overflow-wrap: break-word !important; text-align: center; color: rgb(136, 136, 136); font-size: 14px;">Postman 驗證結果</figcaption>

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

Controller:

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

@RestController
@RequestMapping("/api")
@Validatedpublic 
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
@Validatedpublic 
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

@AutowiredValidator validate

自定以 Validator(實用)

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

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

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

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

@Target({FIELD})
@Retention(RUNTIME)
@Constraint(validatedBy = RegionValidator.class)
@Documentedpublic
 @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
@Validatedpublic 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

  • 原理分析

參考

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容