使用自定义注解进行restful请求参数的校验方式
目录
- 自定义注解进行restful请求参数的校验
- 1、首先我们使用@interface定义一个注解
- 2、实现注解实现类(和@interface定义的注解在同一个包下)
- 3、在需要校验的对象的字段上加上@ByteLength注解
- springboot小技巧:restful接口参数校验,自定义校验规则
- restful风格接口参数校验
- 自定义参数校验注解方法
自定义注解进行restful请求参数的校验 在使用springmvc开发的时候,我们通常会在controller中的方法参数实体类中加上@NotNull()等类似注解,然后在方法参数上加上
@Vilad 注解,这样在有请求的时候,就会自动按照我们的注解进行参数是否合法,避免了我们手工的校验。
但是,自带的校验注解有的时候并不能满足我们的业务验证需求,因此,我们就有必要进行自定义校验注解,以业务为需求定制我们
自己的校验注解。
下面我们来看一个例子:
1、首先我们使用@interface定义一个注解
@Target( { METHOD, FIELD, ANNOTATION_TYPE })@Retention(RUNTIME)@Constraint(validatedBy = ByteLengthValidator.class)// 使用@Constraint指定注解校验实现类,这是一个限制型注解,只能使用指定的实现类@Documentedpublic @interface ByteLength {int min() default 0; int max() default 2147483647; String charsetName() default "GBK"; String message() default "的长度只能在{min}和{max}之间"; Class>[] groups() default {}; Class extends Payload>[] payload() default {}; }
2、实现注解实现类(和@interface定义的注解在同一个包下)
注解实现类需要实现ConstraintValidator 接口
public class ByteLengthValidator implements ConstraintValidator{// 实现ConstraintValidator int min; int max; String charsetName; @Override public void initialize(ByteLength constraintAnnotation) {this.min = constraintAnnotation.min(); this.max = constraintAnnotation.max(); this.charsetName = constraintAnnotation.charsetName(); } @Override public boolean isValid(String value, ConstraintValidatorContext context) {// 实现校验规则if (null == value) {return min <= 0; } try {int length = value.getBytes(charsetName).length; return length >= min && length <= max; } catch (UnsupportedEncodingException e) {e.printStackTrace(); return false; } }}
3、在需要校验的对象的字段上加上@ByteLength注解
然后在接口方法的该对象参数上加上@Vilad 注解,在接收的请求的时候,就会使用
我们自定义的@ByteLength 进行校验该字段。
【使用自定义注解进行restful请求参数的校验方式】
springboot小技巧:restful接口参数校验,自定义校验规则
restful风格接口参数校验
![使用自定义注解进行restful请求参数的校验方式](https://img.it610.com/image/info11/db66009f05bf4fd68473f331e120ee34.jpg)
文章图片
在接收参数的实体类的属性上添加默认的注解或者自定义注解
![使用自定义注解进行restful请求参数的校验方式](https://img.it610.com/image/info11/809eaa634b064eee80970db012680e66.jpg)
文章图片
自定义参数校验注解方法
1>定义自定义注解
![使用自定义注解进行restful请求参数的校验方式](https://img.it610.com/image/info11/ddca6e8749154579b15a5be3ef4f950e.jpg)
文章图片
2>定义参数校验逻辑的处理类
![使用自定义注解进行restful请求参数的校验方式](https://img.it610.com/image/info11/e447170404e94932a42367679402cb4c.jpg)
文章图片
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家.
推荐阅读
- 由浅入深理解AOP
- 【译】20个更有效地使用谷歌搜索的技巧
- mybatisplus如何在xml的连表查询中使用queryWrapper
- MybatisPlus|MybatisPlus LambdaQueryWrapper使用int默认值的坑及解决
- MybatisPlus使用queryWrapper如何实现复杂查询
- SpringBoot调用公共模块的自定义注解失效的解决
- python自定义封装带颜色的logging模块
- iOS中的Block
- Linux下面如何查看tomcat已经使用多少线程
- 使用composer自动加载类文件