温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

springboot如何进行接入参数验证

发布时间:2021-09-29 17:09:03 来源:亿速云 阅读:112 作者:柒染 栏目:大数据

本篇文章为大家展示了springboot如何进行接入参数验证,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

使用环境 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、注解

AnnotationSupported data types作用
NotBlankString验证String 字符串是否为空
NotNullString,Object,Integer,Long,Double,Short,Float,BigDecimal, BigInteger验证对象是否为空
NotEmptyString验证字符串不能为空
AssertFalseBoolean,boolean,String只能为false
AssertTrueBoolean,boolean,String只能为true
BankCardString验证银行卡
CreditCardString验证信用卡
DefaultInteger,Double,Long,Short,Float,BigDecimal,String设置默认值
DigitsString验证是否是数字
EmailString验证是否是邮箱
IdCardString验证是否是身份证,验证18岁
Lengthint,long,short,double,Integer,Long,Float,Double,Short,String验证长度
PatternString正则表达式验证
PhoneString验证手机号是否正确
Sizeint,long,short,Integer,Long,Short验证大小值
NotEqualSizeString验证长度

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";
    }
}


上述内容就是springboot如何进行接入参数验证,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI