1、首先創(chuàng)建一個(gè)測試實(shí)體類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必須為數(shù)字,其值大于或等于指定的最小值")
- private Integer min;
- @Max(value = 10, message = "max必須為數(shù)字,其值小于或等于指定的最大值")
- 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整數(shù)位不能超過4個(gè),小數(shù)位不能超過2個(gè)")
- private BigDecimal digits;
- /**
- * 將前臺傳來的日期數(shù)據(jù)映射到此字段
- */
- @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必須符合正則表達(dá)式")
- 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、封裝返回響應(yīng)體
- 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, "服務(wù)端異常");
- }
- 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> {
- /**
- * 返回狀態(tài)碼 除200其余全部失敗
- */
- private int code;
- /**
- * 返回信息 除success其余全部失敗
- */
- private String msg;
- /**
- * 泛型數(shù)據(jù)
- */
- private T data;
- /**
- * 成功時(shí)返回的類型
- *
- * @param data 數(shù)據(jù)
- * @param <T> 泛型
- * @return 泛型數(shù)據(jù)
- */
- 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、創(chuàng)建使用增強(qiáng)器攔截并返回異常信息
- 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) {
- // 拿到參數(shù)校驗(yàn)具體異常信息
- errMsg = Objects.requireNonNull(((MethodArgumentNotValidException) e).getBindingResult().getFieldError()).getDefaultMessage();
- }
- return Result.fail(new CodeMsg(500, errMsg));
- }
- }
4、創(chuàng)建控制層測試
- 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、測試符合驗(yàn)證請求體訪問,請求體如下:
- {
- "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、故意修改不符合驗(yàn)證的數(shù)據(jù)
7、如果想做整體驗(yàn)證,如下:
- 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整體校驗(yàn)工具類
- *
- * @author 方延杰
- * @version 1.0
- * @since 2020/12/10 10:08 下午
- */
- public class ValidatorUtils {
- private static final Validator VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();
- /**
- * Bean整體校驗(yàn),有不合規(guī)范,拼接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) {
- //如果存在錯(cuò)誤結(jié)果,則將其解析并進(jìn)行拼湊后異常拋出
- List<String> errorMessageList = resultSet.stream().map(ConstraintViolation::getMessage).collect(Collectors.toList());
- errorMessageList.forEach(o -> errorMessage.append(o).append(";"));
- }
- return errorMessage.toString();
- }
- }
8、整體測試類
到此這篇關(guān)于詳解Java后端優(yōu)雅驗(yàn)證參數(shù)合法性的文章就介紹到這了,更多相關(guān)Java 驗(yàn)證參數(shù)合法性內(nèi)容請搜索我們以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://blog.csdn.net/weixin_48314739/article/details/111012090