• 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   

    如此便是完成了自定义注解,将统一异常处理即可.

    一切没有栗子的讲解都是耍流氓

  • 相关阅读:
    UML建模之用例图关系
    python模块介绍
    Delphi操作XML(七)
    Delphi操作XML(一)
    Delphi操作XML(五)
    Delphi操作XML(六)
    Delphi操作XML(二)
    Delphi操作XML(四)
    Delphi操作XML(三)
    决心好好写cnblogs
  • 原文地址:https://www.cnblogs.com/xxmyz/p/10115498.html
Copyright © 2020-2023  润新知