当前位置: 首页 > 科技观察

Springboot中的优雅字段验证

时间:2023-03-15 20:21:49 科技观察

前段时间提交代码审查,同事提到一个代码规范缺陷:参数验证应该放在controller层。参数校验应该怎么做?Controller层VSService层我在网上查了一些资料。一般建议将校验放在与业务无关的Controller层,将校验放在与业务相关的Service层。那么如何把参数校验写的优雅漂亮,如果都是if-else,感觉代码很low,还好有轮子可以用。常用验证工具使用HibernateValidate引入依赖org.hibernatehibernate-validator4.3.1.Final常用该注解表示使用姿势需要在Controller中配合@Validated或@Valid注解使用。@Validated和@Valid注解的区别不是很大。一般来说,你可以选择一个。区别如下:虽然@Validated比@Valid更强大,在@Valid之上提供了分组功能和验证排序功能,但从未在实际项目中使用过。Hibernate-validate框架中的注解需要添加到实体中一起使用。~定义一个实体:publicclassDataSetSaveVO{//唯一标识为空@NotBlank(message="useruuidisempty")//用户名只能是字母和数字@Pattern(regexp="^[a-z0-9]+$",message="usernamescanonlybealphabeticandnumeric")@Length(max=48,message="useruuidlengthover48byte")privateStringuserUuid;//数据集名称只能是字母和数字@Pattern(regexp="^[A-Za-z0-9]+$",message="datasetnamescanonlybelettersandNumbers")//文件名太长@Length(max=48,message="filenametoolong")//文件名为空@NotBlank(message="filenameisempty")privateStringname;//数据集描述最多256字节@Length(max=256,message="datasetdescriptionlengthover256byte")//数据集描述为空@NotBlank(message="datasetdescriptionisnull")privateStringdescription;}描述:当message字段不满足校验规则时抛出异常信息。~Controller层方法:@PostMappingpublicResponseVOcreateDataSet(@Valid@RequestBodyDataSetSaveVOdataSetVO){returnResponseUtil.success(dataSetService.saveDataSet(dataSetVO));}描述:在验证实体DataSetSaveVO旁边添加@Valid或@Validated注解。使用commons-lang3引入依赖org.apache.commonscommons-lang33.4常用方法说明测试代码//StringUtils.isEmptySystem.out.println(StringUtils.isEmpty(""));//trueSystem.out.println(StringUtils.isEmpty(""));//false//StringUtils.isNotEmptySystem.out.println(StringUtils.isNotEmpty(""));//false//StringUtils.isBlankSystem.out.println(StringUtils.isBlank(""));//trueSystem.out.println(StringUtils.isBlank(""));//true//StringUtils.isNotBlankSystem.out.println(StringUtils.isNotBlank(""));//falseListemptyList=newArrayList<>();ListnullnullList=null;ListnotEmptyList=newArrayList<>();notEmptyList.add(1);//CollectionUtils.isEmptySystem.out.println(CollectionUtils.isEmpty(emptyList));//trueSystem.out.println(CollectionUtils.isEmpty(nullList));//trueSystem.out.println(CollectionUtils.isEmpty(notEmptyList));//false//CollectionUtils.isNotEmptySystem.out.println(CollectionUtils.isNotEmpty(emptyList));//falseSystem.out.println(CollectionUtils.isNotEmpty(nullList));//falseSystem.out.println(CollectionUtils.isNotEmpty(notEmptyList));//真正的自定义注解当以上几个方面不能满足验证要求时,可以考虑使用自定义注解