springmvcspringboot简单轻量好用的参数验证。支持基本类型查参数验证。支持自定义注解的参数验证。使用简单方便。
使用4步配置
1、导入jar
<dependency><groupId>com.github.fashionbrot</groupId><artifactId>mars-validated</artifactId><version>1.0.0</version></dependency>2、使用注解
2.1springboot配置
@SpringBootApplication@EnableValidatedConfig(fileName="valid_zh_CN")publicclassDemoApplication{publicstaticvoidmain(String[]args){SpringApplication.run(DemoApplication.class,args);}}2.2spring配置
@Component@Configuration@EnableValidatedConfig(fileName="valid_zh_CN")publicclassConfig{}3、使用@Validated开启接口验证@Email验证邮箱格式
@ControllerpublicclassDemoController{@AutowiredprivateTestServicetestService;@RequestMapping("/emailCheck")@ResponseBody@Validated//注意此处publicStringdemo(@EmailStringabc,){returntestService.test(abc);}}@ControllerpublicclassDemoController{@AutowiredprivateTestServicetestService;@RequestMapping("/idcardCheck")@ResponseBody@ValidatedpublicStringdemo(IdCardModelidCardModel){returntestService.test("ac");}@RequestMapping("/idcardCheck2")@ResponseBodypublicStringdemo2(IdCardModelidCardModel){returntestService.test2("ac");}}**此处支持多继承验证***publicclassIdCardModelextendsBaseModel{@IdCardprivateStringidCardModel;publicStringgetIdCardModel(){returnidCardModel;}publicvoidsetIdCardModel(StringidCardModel){this.idCardModel=idCardModel;}}@ServicepublicclassTestService{@Validatedpublicvoidtest2(@IdCardStringabc){}}4、自定义实现全局异常处理
拦截com.fashion.spv.validated.exception.ValidatedException
@RestControllerAdvicepublicclassGlobalExceptionHandler{@ExceptionHandler(ValidatedException.class)@ResponseStatus(HttpStatus.OK)publicRespMessageValidationException(ValidatedExceptione){returnnewRespMessage(-100,e.getMsg());}}validated参数验证
使用环境
spring4.0及以上jdk1.8及以上
AnnotationSupporteddatatypes作用NotBlankString验证String字符串是否为空NotNullString,Object,Integer,Long,Double,Short,Float,BigDecimal,BigInteger验证对象是否为空AssertFalseBoolean,boolean,String只能为falseAssertTrueBoolean,boolean,String只能为trueBankCardString验证银行卡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验证大小值支持自定义注解如下:1、实现ConstraintValidator此接口2、自定义注解如下:CustomConstraintValidator.class,CustomConstraintValidator2.class实现类可多个,至少有一个@Documented@Target({ElementType.FIELD,ElementType.PARAMETER})@Retention(RetentionPolicy.RUNTIME)@Constraint(validatedBy={CustomConstraintValidator.class,CustomConstraintValidator2.class})public@interfaceCustom{Stringmsg()default"com.spv.valid.Custom.msg";intmin();}3、代码实现publicclassCustomConstraintValidatorimplementsConstraintValidator<Custom,String>{@OverridepublicbooleanisValid(Customcustom,Stringvar1){/***自定义方法*/intmin=custom.min();/***value*/System.out.println(var1);/***returntrue则验证成功false验证失败*/returntrue;}}
评论