springboot 接入参数验证

原创
2020/09/21 15:38
阅读数 182

使用环境 jdk1.8 spring 4及以上

1、添加jar 包

        <dependency>
            <groupId>com.github.fashionbrot</groupId>
            <artifactId>mars-validated</artifactId>
            <version>1.0.2</version>
        </dependency>

2、开启使用 valid 2种方式

@SpringBootApplication
@EnableValidatedConfig(fileName = "test")  // fileName 默认中文jar包自带 如需要批量自定义请自己创建 test.properties  放在自己项目中的resources 下
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
@Component
@Configuration
@EnableValidatedConfig(fileName = "valid_zh_CN") //默认读取 mars-validated  resources 下的 valid_zh_CN,所以不写默认读取中文
public class ValidConfig {
}

3、自定义实现全局异常处理

拦截 ValidatedException异常类

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public RespVo exception(Exception e) {
        log.error("exception error:",e);
        return RespVo.fail(RespCode.FAIL.getMsg());
    }
    /**
     * 参数验证全局处理
     * @param e
     * @return
     */
    @ExceptionHandler(ValidatedException.class)
    @ResponseStatus(HttpStatus.OK)
    public RespVo ValidationException(ValidatedException e){
        if (log.isDebugEnabled()){
            log.debug("filedName:{} errorMsg:{}",e.getFieldName(),e.getMsg());
        }
        return RespVo.fail(e.getMsg(),RespCode.PARAMETER_ERROR.getCode());
    }
}

4、开始使用 @Validated //接口开启验证

@Controller
public class TestController {

    @Autowired
    private ValidService validService;

    @RequestMapping("/test")
    @ResponseBody
    @Validated //接口开启验证
    public String test( String abc,@Custom(min = 1,msg="请求参数失败") String abc1){
        return abc+":"+abc1;
    }
    //group 验证参数
    @RequestMapping("/test1")
    @ResponseBody
    @Validated(groups = {EditGroup.class})
    public String test1( @Custom(min = 1,groups = {EditGroup.class,AddGroup.class}) String abc1){
        return abc1;
    }

    //group 验证 bean
    @RequestMapping("/test2")
    @ResponseBody
    @Validated(groups = AddGroup.class)
    public String test2(GroupModel groupModel){
        return groupModel.getAbc();
    }
}

5、注解

Annotation Supported data types 作用
NotBlank String 验证String 字符串是否为空
NotNull String,Object,Integer,Long,Double,Short,Float,BigDecimal, BigInteger 验证对象是否为空
NotEmpty String 验证字符串不能为空
AssertFalse Boolean,boolean,String 只能为false
AssertTrue Boolean,boolean,String 只能为true
BankCard String 验证银行卡
CreditCard String 验证信用卡
Default Integer,Double,Long,Short,Float,BigDecimal,String 设置默认值
Digits String 验证是否是数字
Email String 验证是否是邮箱
IdCard String 验证是否是身份证,验证18岁
Length int,long,short,double,Integer,Long,Float,Double,Short,String 验证长度
Pattern String 正则表达式验证
Phone String 验证手机号是否正确
Size int,long,short,Integer,Long,Short 验证大小值
NotEqualSize String 验证长度

6、自定义注解

(1)定义注解

@Documented
@Target({ElementType.FIELD,  ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {CustomConstraintValidator.class,CustomConstraintValidator2.class})//可对应多个或一个实现类
//CustomConstraintValidator 实现类1
//CustomConstraintValidator2 实现类2
public @interface Custom {

//com.sgr.valid.Custom.msg  jar包下的 valid_zh_CN.properties 下对应的msg
    String msg() default "com.sgr.valid.Custom.msg";

    int min();

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

(2)实现类 CustomConstraintValidator 如同 CustomConstraintValidator2

public class CustomConstraintValidator implements ConstraintValidator<Custom, Object> {

    @Override
    public boolean isValid(Custom custom, Object var1) {
        /**
         * 自定义方法
         */
        int min=custom.min();
        /**
         * valud
         */
        System.out.println(var1);
        var1="567";
        /**
         * return true 则验证成功 false 验证失败
          */
        return false;
    }

   //可实现对参数的修改
    @Override
    public Object modify(Custom annotation, Object var) {
        System.out.println("CustomConstraintValidator:"+var);
        return var+"1";
    }
}

demo 可以下载 https://github.com/fashionbrot/mars-validated/tree/master/test 参考

希望多多支持,功能正在不断增加

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
0 收藏
0
分享
返回顶部
顶部