SpringBoot集成Validation參數校驗

本文實例為大傢分享瞭SpringBoot集成Validation參數校驗的具體代碼,供大傢參考,具體內容如下

1、依賴

SpringBoot在web啟動器中已經包含validator包

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

非SpringBoot項目,需要自定引入依賴

<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.1.5.Final</version>
</dependency>
<dependency>
    <groupOd>org.glassfish</groupId>
    <artifactId>jakarta.el</artifactId>
    <version>3.0.3</version>
</dependency>

2、常用約束說明

package com.smile.project.validator.utils;
 
public class 常用約束說明 {
 
    /**
     * @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=):指定的正則表達式
     * @URL:必須是一個URL
     * @Email:必須是email格式
     * @NotBlank:字符串不能為空
     * @NotEmpty:集合不能為空
     * @Length:長度必須在指定范圍內
     * @Valid:對實體類進行校驗
     */
 
}

3、實體約束示例

import com.smile.project.validator.utils.Gender;
import lombok.Data;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
 
@Data
public class SysUser {
 
    private Long id;
 
    @NotNull(message = "用戶名不能為空")
    @Size(min = 3,max = 5,message = "用戶名長度為{min}-{max}之間")
    private String username;
 
    @NotNull(message = "昵稱不能為空")
    private String name;
 
    @NotNull(message = "密碼不能為空")
    private String password;
 
    @Email(message = "郵箱格式不合法")
    private String email;
 
    private String gender;
 
}

4、控制層示例

需要在class加上@Validated註解

如果參數時實體,需要加上@Valid註解

import com.smile.project.validator.entity.SysUser;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
 
@RestController
@Validated
public class SysUserController {
 
    /**
     * 方法參數為實體校驗
     */
    @PostMapping("/register")
    public ResponseEntity register(@Valid SysUser sysUser){
        return ResponseEntity.ok(sysUser);
    }
 
    /**
     * 方法參數校驗
     */
    @GetMapping("user")
    public ResponseEntity getUser(@NotNull(message = "用戶名不能為空") String username){
        SysUser sysUser = new SysUser();
        sysUser.setName("smile");
        return ResponseEntity.ok(sysUser);
    }
 
}

5、異常捕獲

全局異常捕獲,當出現參數校驗不合法時捕獲異常,並且返回給前端

import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
 
/**
 * 全局異常捕獲
 * 當出翔參數校驗不合法時捕獲異常,並且返回給前端
 */
@ControllerAdvice
public class GlobHandler {
 
    /**
     * 捕獲方法參數校驗異常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public ResponseEntity constraintViolationExceptionHandler(ConstraintViolationException e){
        Set<ConstraintViolation<?>> message = e.getConstraintViolations();
        HashMap<String,Object> map = new HashMap<>();
        message.stream().forEach(msg ->{
            String path = msg.getPropertyPath().toString();
            String field = path.substring(path.indexOf(".")+1);
            map.put(field,msg.getMessageTemplate());
        });
        return ResponseEntity.ok(map);
    }
 
    /**
     * 捕獲實體參數校驗異常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResponseEntity resolveMethodArgumentNotValidException(MethodArgumentNotValidException e){
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        HashMap<String,Object> map = new HashMap<>();
        allErrors.stream().forEach(error -> {
            FieldError fieldError = (FieldError) error;
            map.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        return ResponseEntity.ok(map);
    }
 
}

6、自定義校驗規則

特殊的字段需要自定義規則,比如身份證號碼,郵箱,電話等

6.1、定義校驗註解

import com.smile.project.validator.utils.GenderValidator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
 
/**
 * 定義校驗註解
 */
@Target({METHOD,FIELD})
@Retention(RUNTIME)
@Constraint(validatedBy = GenderValidator.class)
@Documented
public @interface Gender {
 
    String message() default "性別為男或者女";
 
    Class<?>[] groups() default {};
 
    Class<? extends Payload[]>[] payload() default {};
 
}

6.2、GenderValidator實現ConstraintValidator接口並提供校驗規則

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
 
/**
 * 實現ConstraintValidator接口並提供校驗規則
 */
public class GenderValidator implements ConstraintValidator<Gender,String> {
 
    //初始化校驗值
    @Override
    public void initialize(Gender constraintAnnotation) {
 
    }
 
    //檢驗規則
    @Override
    public boolean isValid(String value, ConstraintValidatorContext content) {
        return "男".equals(value) || "女".equals(value);
    }
}

6.3、在成員變量中使用註解

import com.smile.project.validator.utils.Gender;
import lombok.Data;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
 
@Data
public class SysUser {
 
    private Long id;
 
    @NotNull(message = "用戶名不能為空")
    @Size(min = 3,max = 5,message = "用戶名長度為{min}-{max}之間")
    private String username;
 
    @NotNull(message = "昵稱不能為空")
    private String name;
 
    @NotNull(message = "密碼不能為空")
    private String password;
 
    @Email(message = "郵箱格式不合法")
    private String email;
 
    @Gender()
    private String gender;
 
}

7、分組校驗

默認情況下,不指定分組都屬於默認組;使用分組校驗有利於分層校驗開發

7.1、新建兩個接口,一個用於查詢,一個用於添加

public interface ADD extends Default {
 
}
 
public interface Select extends Default {
 
}

7.2、修改屍體校驗規則,如果不指定分組默認時Default組;

import com.smile.project.validator.utils.Gender;
import lombok.Data;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
 
@Data
public class SysUser {
 
    private Long id;
 
    @NotNull(message = "用戶名不能為空",groups = ADD.class)
    @Size(min = 3,max = 5,message = "用戶名長度為{min}-{max}之間")
    private String username;
 
    @NotNull(message = "昵稱不能為空",groups = Select.class)
    private String name;
 
    @NotNull(message = "密碼不能為空",groups = ADD.class)
    private String password;
 
    @Email(message = "郵箱格式不合法",groups = Select.class)
    private String email;
 
    @Gender()
    private String gender;
 
}

7.3、控制層示例,此時隻會校驗ADD組和Default組

//分組校驗
@PostMapping("/user")
public ResponseEntity addUser(@Validated(value = ADD.class) @RequestBody SysUser sysUser){
    return ResponseEntity.ok(sysUser);
}

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: