spring注解式參數校驗


很痛苦遇到大量的參數進行校驗,在業務中還要拋出異常或者

返回異常時的校驗信息,在代碼中相當冗長,今天我們就來學習spring注解式參數校驗.

其實就是:hibernate的validator.

開始啦......

1.controller的bean加上@Validated就像這樣

1     @ApiOperation(value = "用戶登錄接口", notes = "用戶登錄")
2     @PostMapping("/userLogin")
3     public ResponseDTO<UserResponseDTO> userLogin(@RequestBody @Validated RequestDTO<UserLoginRequestDTO> requestDto) {
4         return userBizService.userLogin(requestDto);
5     }

 

2.下面是一些簡單的例子:如在Bean中添加注解:

 

 1 @Data
 2 public class UserDTO implements Serializable {
 3     private static final long serialVersionUID = -7839165682411118398L;
 4 
 5 
 6     @NotBlank(message = "用戶名不能為空")
 7     @Length(min=5, max=20, message="用戶名長度必須在5-20之間")
 8     @Pattern(regexp = "^[a-zA-Z_]\\w{4,19}$", message = "用戶名必須以字母下划線開頭,可由字母數字下划線組成")
 9     private String username;
10 
11     @NotBlank(message = "密碼不能為空")
12     @Length(min = 24, max = 44, message = "密碼長度范圍為6-18位")
13     private String password;
14 
15     @NotBlank(message = "手機號不能為空")
16     @Pattern(regexp = "^[1][3,4,5,6,7,8,9][0-9]{9}$", message = "手機號不合法")
17     private String phone;
18 
19     @Email(message = "郵箱格式不正確")
20     private String email;
21 
22     @NotNull(message = "簡介編號不能為空")
23     @NotEmpty(message = "簡介編號不能為空")
24     private List<Integer> introList;
25 
26     @Range(min=0, max=4,message = "基礎規格")
27     private int scale;
28 
29     @NotNull(message = "比例不能為空")
30     @DecimalMax(value = "100", message = "最大比率是100%啦~")
31     @DecimalMin(value = "0.01", message = "最小比率是0.01%啦~")
32     private Double cashbackRatio;
38 }

 

3.最后我們要進行切面配置,處理校驗類的異常:

 1 import com.cn.GateWayException;
 2 import com.cn.alasga.common.core.dto.ResponseDTO;
 3 import com.cn.ResponseCode;
 4 import com.cn.alasga.common.core.exception.BizException;
 5 import com.cn.TokenException;
 6 import org.slf4j.Logger;
 7 import org.slf4j.LoggerFactory;
 8 import org.springframework.http.converter.HttpMessageNotReadableException;
 9 import org.springframework.util.StringUtils;
10 import org.springframework.web.bind.MethodArgumentNotValidException;
11 import org.springframework.web.bind.annotation.ExceptionHandler;
12 import org.springframework.web.bind.annotation.RestControllerAdvice;
13 
14 import javax.validation.ValidationException;
15 import java.util.regex.Matcher;
16 import java.util.regex.Pattern;
17 
18 /**
19  * @author Lijing
20  * @ClassName: ExceptionHandlerController.class
21  * @Description: 統一異常處理類
22  * @date 2017年8月9日 下午4:44:25
23  */
24 @RestControllerAdvice
25 public class ExceptionHandlerController {
26 
27     private Logger log = LoggerFactory.getLogger(ExceptionHandlerController.class);
28 
29     private final static Pattern PATTERN = Pattern.compile("(\\[[^]]*])");
30 
31 
32     @ExceptionHandler(Exception.class)
33     public ResponseDTO handleException(Exception exception) {
34 
35         if (exception instanceof GateWayException) {
36             GateWayException gateWayException = (GateWayException) exception;
37             return new ResponseDTO<>(gateWayException);
38         }
39 
40         if (exception instanceof BizException) {
41             BizException biz = (BizException) exception;
42             return new ResponseDTO<>(biz);
43         }
44 
45         if (exception instanceof MethodArgumentNotValidException) {
46             MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException) exception;
47             return new ResponseDTO<>(methodArgumentNotValidException.getBindingResult().getFieldError()
48                     .getDefaultMessage(), ResponseCode.PARAM_FAIL, ResponseDTO.RESPONSE_ID_PARAM_EXCEPTION_CODE);
49         }
50 
51         if (exception instanceof ValidationException) {
52             if (exception.getCause() instanceof TokenException) {
53                 TokenException tokenException = (TokenException) exception.getCause();
54                 return new ResponseDTO<>(tokenException);
55             }
56         }
57 
58         if (exception instanceof org.springframework.web.HttpRequestMethodNotSupportedException) {
59             return new ResponseDTO<>(ResponseCode.HTTP_REQUEST_METHOD_NOT_SUPPORTED);
60         }
61 
62         if (exception instanceof HttpMessageNotReadableException) {
63             log.error(exception.getMessage());
64             return new ResponseDTO<>(ResponseCode.HTTP_REQUEST_PARAMETER_INVALID_FORMAT);
65         }
66 
67         if (!StringUtils.isEmpty(exception.getMessage())) {
68             Matcher m = PATTERN.matcher(exception.getMessage());
69             if (m.find()) {
70                 String[] rpcException = m.group(0).substring(1, m.group().length() - 1).split("-");
71                 Integer code;
72                 try {
73                     code = Integer.parseInt(rpcException[0]);
74                 } catch (Exception e) {
75                     log.error(exception.getMessage(), exception);
76                     return new ResponseDTO<>(ResponseDTO.RESPONSE_ID_BIZ_EXCEPTION_CODE, ResponseCode.RESPONSE_TIME_OUT);
77                 }
78                 return new ResponseDTO<>(ResponseDTO.RESPONSE_ID_BIZ_EXCEPTION_CODE, code, rpcException[1]);
79             }
80         }
81 
82         //主要輸出不確定的異常
83         log.error(exception.getMessage(), exception);
84 
85         return new ResponseDTO<>(exception);
86     }
87 
88 }

 

MethodArgumentNotValidException 就是我們的 豬腳了 ,他負責獲取這些參數校驗中的異常,
ValidationException 是javax.的校驗,和今天的校驗也是有關系的,很久了,我都忘記驗證了.

 

4.下面簡單的解釋一些常用的規則示意:

 1.@NotNull:不能為null,但可以為empty(""," "," ") 
2.@NotEmpty:不能為null,而且長度必須大於0 (" "," ")
 3.@NotBlank:只能作用在String上,不能為null,而且調用trim()后,長度必須大於0("test") 即:必須有實際字符


5.是不是很簡單: 學會了就去點個贊

驗證注解

驗證的數據類型

說明

@AssertFalse

Boolean,boolean

驗證注解的元素值是false

@AssertTrue

Boolean,boolean

驗證注解的元素值是true

@NotNull

任意類型

驗證注解的元素值不是null

@Null

任意類型

驗證注解的元素值是null

@Min(value=值)

BigDecimal,BigInteger, byte,

short, int, long,等任何Number或CharSequence(存儲的是數字)子類型

驗證注解的元素值大於等於@Min指定的value值

@Max(value=值)

和@Min要求一樣

驗證注解的元素值小於等於@Max指定的value值

@DecimalMin(value=值)

和@Min要求一樣

驗證注解的元素值大於等於@ DecimalMin指定的value值

@DecimalMax(value=值)

和@Min要求一樣

驗證注解的元素值小於等於@ DecimalMax指定的value值

@Digits(integer=整數位數, fraction=小數位數)

和@Min要求一樣

驗證注解的元素值的整數位數和小數位數上限

@Size(min=下限, max=上限)

字符串、Collection、Map、數組等

驗證注解的元素值的在min和max(包含)指定區間之內,如字符長度、集合大小

@Past

java.util.Date,

java.util.Calendar;

Joda Time類庫的日期類型

驗證注解的元素值(日期類型)比當前時間早

@Future

與@Past要求一樣

驗證注解的元素值(日期類型)比當前時間晚

@NotBlank

CharSequence子類型

驗證注解的元素值不為空(不為null、去除首位空格后長度為0),不同於@NotEmpty,@NotBlank只應用於字符串且在比較時會去除字符串的首位空格

@Length(min=下限, max=上限)

CharSequence子類型

驗證注解的元素值長度在min和max區間內

@NotEmpty

CharSequence子類型、Collection、Map、數組

驗證注解的元素值不為null且不為空(字符串長度不為0、集合大小不為0)

@Range(min=最小值, max=最大值)

BigDecimal,BigInteger,CharSequence, byte, short, int, long等原子類型和包裝類型

驗證注解的元素值在最小值和最大值之間

@Email(regexp=正則表達式,

flag=標志的模式)

CharSequence子類型(如String)

驗證注解的元素值是Email,也可以通過regexp和flag指定自定義的email格式

@Pattern(regexp=正則表達式,

flag=標志的模式)

String,任何CharSequence的子類型

驗證注解的元素值與指定的正則表達式匹配

@Valid

任何非原子類型

指定遞歸驗證關聯的對象;

如用戶對象中有個地址對象屬性,如果想在驗證用戶對象時一起驗證地址對象的話,在地址對象上加@Valid注解即可級聯驗證

 

此處只列出Hibernate Validator提供的大部分驗證約束注解,請參考hibernate validator官方文檔了解其他驗證約束注解和進行自定義的驗證約束注解定義。

6.是不是很簡單: 我再教你看源碼:

ValidationMessages.properties 就是校驗的message,就可以順着看下去了!!!

7.補充 自定義注解

很簡單 找源碼抄一份注解 比如我們來個 自定義身份證校驗 注解

來 注解走起

@Documented
@Target({ElementType.PARAMETER, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = IdentityCardNumberValidator.class)
public @interface IdentityCardNumber {

    String message() default "身份證號碼不合法";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

再實現校驗接口

public class IdentityCardNumberValidator implements ConstraintValidator<IdentityCardNumber, Object> {

    @Override
    public void initialize(IdentityCardNumber identityCardNumber) {
    }

    @Override
    public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
        return IdCardValidatorUtils.isValidate18Idcard(o.toString());
    }
}

最后 注解隨便貼 IdCardValidatorUtils 是自己寫的工具類 網上大把~  需要的可以加我vx: cherry_D1314   

如此便是完成了自定義注解,將統一異常處理即可.

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM