spring註解式參數校驗

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

返回異常時的校驗信息,在代碼中至關冗長,今天咱們就來學習spring註解式參數校驗.git

其實就是:hibernate的validator.web

開始啦......正則表達式

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

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.最後咱們要進行切面配置,處理校驗類的異常:app

 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.下面簡單的解釋一些經常使用的規則示意:ide

 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   

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

相關文章
相關標籤/搜索