詳解Java後端優雅驗證參數合法性

1、首先創建一個測試實體類Person,並攜帶如上註解,其註解的作用描述在message

package com.clickpaas.pojo;

import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.Range;

import javax.validation.constraints.*;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author 方延傑
 * @version 1.0
 * @since 2020/12/10 9:04 下午
 */
@Data
public class Person {

  @Null(message = "death必須為null")
  private String death;

  @AssertTrue(message = "bool必須為true")
  private boolean bool;

  @AssertFalse(message = "fal必須為false")
  private boolean fal;

  @Min(value = 1, message = "min必須為數字,其值大於或等於指定的最小值")
  private Integer min;

  @Max(value = 10, message = "max必須為數字,其值小於或等於指定的最大值")
  private Integer max;

  @DecimalMin(value = "1", message = "minDeci最小不能小於1")
  private BigDecimal minDeci;

  @DecimalMax(value = "10", message = "maxDeci最大不能大於10")
  private BigDecimal maxDeci;

  @Size(min = 1, max = 2, message = "list集合的長度最小不能小於1,最大不能大於2")
  private List<Object> list;

  @Digits(integer = 4, fraction = 2, message = "digits整數位不能超過4個,小數位不能超過2個")
  private BigDecimal digits;

  /**
   * 將前臺傳來的日期數據映射到此字段
   */
  @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
  @Past(message = "past必須為過去的日期")
  private Date past;

  @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
  @Future(message = "future必須為將來的日期")
  private Date future;

  @Pattern(regexp = "^1[3|4|5|7|8][0-9]{9}$", message = "phone必須符合正則表達式")
  private String phone;

  @Email(message = "email必須是郵箱格式")
  private String email;

  @Length(min = 1, max = 2, message = "length長度最小不能小於1,最大不能大於2")
  private String length;

  @NotEmpty(message = "id不能為null,長度大於0")
  private String id;

  @Range(min = 1, max = 12, message = "month最小不能小於1,最大不能大於12")
  private Integer month;

  @NotBlank(message = "name不能為null,字段串長度大於0(限字符串)")
  private String name;
}

2、封裝返回響應體

package com.clickpaas.response;

import lombok.AllArgsConstructor;
import lombok.Data;

/**
 * @author 方延傑
 * @version 1.0
 * @since 2019/7/3 4:32 下午
 */
@Data
@AllArgsConstructor
public class CodeMsg {

  private int code;

  private String msg;

  /**
   * 失敗
   */
  public static CodeMsg SERVER_ERROR = new CodeMsg(500, "服務端異常");

}
package com.clickpaas.response;

import lombok.AllArgsConstructor;
import lombok.Data;

/**
 * @author 方延傑
 * @version 1.0
 * @since 2019/7/3 4:35 下午
 */
@Data
@AllArgsConstructor
public class Result<T> {

  /**
   * 返回狀態碼 除200其餘全部失敗
   */
  private int code;

  /**
   * 返回信息 除success其餘全部失敗
   */
  private String msg;

  /**
   * 泛型數據
   */
  private T data;

  /**
   * 成功時返回的類型
   *
   * @param data 數據
   * @param <T> 泛型
   * @return 泛型數據
   */
  public static <T> Result<T> success(T data) {
    return new Result<>(200, "success", data);
  }

  public static <T> Result<T> fail(CodeMsg codeMsg) {
    return new Result<>(codeMsg);
  }
  private Result(CodeMsg codeMsg) {
    if (codeMsg == null) {
      return;
    }
    this.code = codeMsg.getCode();
    this.msg = codeMsg.getMsg();
  }

}

3、創建使用增強器攔截並返回異常信息

package com.clickpaas.config;

import com.clickpaas.response.CodeMsg;
import com.clickpaas.response.Result;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @author 方延傑
 * @version 1.0
 * @since 2018/12/10 4:59 下午
 */
@RestControllerAdvice
public class GlobalExceptionInterceptor {

  @ExceptionHandler(value = MethodArgumentNotValidException.class)
  public Result<Object> exceptionHandler(HttpServletRequest request, Exception e) {
    String errMsg = "處理失敗";
    if (e instanceof MethodArgumentNotValidException) {
      // 拿到參數校驗具體異常信息
      errMsg = Objects.requireNonNull(((MethodArgumentNotValidException) e).getBindingResult().getFieldError()).getDefaultMessage();
    }
    return Result.fail(new CodeMsg(500, errMsg));
  }
}

4、創建控制層測試

package com.clickpaas.controller;

import com.clickpaas.pojo.Person;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 方延傑
 * @version 1.0
 * @since 2020/12/10 9:03 下午
 */
@RestController
public class ValidController {

  @PostMapping("/valid")
  public String valid(@Validated @RequestBody Person person) {
    return "success";
  }

}

5、測試符合驗證請求體訪問,請求體如下:

{
  "death":null,
  "bool":true,
  "fal":false,
  "min":1,
  "max":10,
  "minDeci":1,
  "maxDeci":10,
  "list":[
    {},{}
  ],
  "digits":1144.12,
  "past":"2020-10-01 10:00:00",
  "future":"2022-10-01 10:00:00",
  "phone":"15900445584",
  "email":"[email protected]",
  "length":"ab",
  "id":" ",
  "name":"a"
}

在這裡插入圖片描述

6、故意修改不符合驗證的數據

在這裡插入圖片描述

7、如果想做整體驗證,如下:

package com.clickpaas.uitl;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Bean整體校驗工具類
 *
 * @author 方延傑
 * @version 1.0
 * @since 2020/12/10 10:08 下午
 */
public class ValidatorUtils {

  private static final Validator VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();

  /**
   * Bean整體校驗,有不合規范,拼接message
   */
  public static String validate(Object obj, Class<?>... groups) {

    StringBuilder errorMessage = new StringBuilder();

    Set<ConstraintViolation<Object>> resultSet = VALIDATOR.validate(obj, groups);
    if (resultSet.size() > 0) {
      //如果存在錯誤結果,則將其解析並進行拼湊後異常拋出
      List<String> errorMessageList = resultSet.stream().map(ConstraintViolation::getMessage).collect(Collectors.toList());
      errorMessageList.forEach(o -> errorMessage.append(o).append(";"));
    }
    return errorMessage.toString();
  }

}

8、整體測試類

在這裡插入圖片描述

到此這篇關於詳解Java後端優雅驗證參數合法性的文章就介紹到這瞭,更多相關Java 驗證參數合法性內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: