Springboot中如何优雅的进行字段校验

沙海 2021年7月15日01:06:20Java评论33字数 3668阅读12分13秒阅读模式
摘要

Springboot中如何优雅的进行字段校验 Java学习者社区

Springboot中如何优雅的进行字段校验

Java学习者社区 文章源自JAVA秀-https://www.javaxiu.com/37896.html

Springboot中如何优雅的进行字段校验文章源自JAVA秀-https://www.javaxiu.com/37896.html

来源:juejin.cn/post/6913735652806754311文章源自JAVA秀-https://www.javaxiu.com/37896.html

前段时间提交代码审核,同事提了一个代码规范缺陷:参数校验应该放在controller层。到底应该如何做参数校验呢文章源自JAVA秀-https://www.javaxiu.com/37896.html

Controller层 VS Service层

去网上查阅了一些资料,一般推荐与业务无关的放在Controller层中进行校验,而与业务有关的放在Service层中进行校验。那么如何将参数校验写的优雅美观呢,如果都是if - else,就感觉代码写的很low,还好有轮子可以使用文章源自JAVA秀-https://www.javaxiu.com/37896.html

常用校验工具类

使用Hibernate Validate

引入依赖文章源自JAVA秀-https://www.javaxiu.com/37896.html

<dependency>    <groupId>org.hibernate</groupId>    <artifactId>hibernate-validator</artifactId>    <version>4.3.1.Final</version></dependency>

常用注解说明文章源自JAVA秀-https://www.javaxiu.com/37896.html

注解说明
@Length(min=,max=)检查所属的字段的长度是否在min和max之间,只能用于字符串
@Range(min=,max=,message=)被注释的元素必须在合适的范围内
@Max该字段的值只能小于或等于该值
@Min该字段的值只能大于或等于该值
@NotNull不能为null
@NotBlank不能为空,检查时会将空格忽略
@NotEmpty不能为空,这里的空是指空字符串
@Pattern(regex=,flag=)被注释的元素必须符合指定的正则表达式

使用姿势需要搭配在Controller中搭配@Validated或@Valid注解一起使用,@Validated和@Valid注解区别不是很大,一般情况下任选一个即可,区别如下:文章源自JAVA秀-https://www.javaxiu.com/37896.html

注解@Validated@Valid
所属的包属于org.springframework.validation.annotation包下的,是spring提供的属于javax.validation包下,是jdk给提供的
是否支持分组和排序

虽然@Validated比@Valid更加强大,在@Valid之上提供了分组功能和验证排序功能,不过在实际项目中一直没有用到过 Hibernate-validate框架中的注解是需要加在实体中一起使用的文章源自JAVA秀-https://www.javaxiu.com/37896.html

  • 定义一个实体文章源自JAVA秀-https://www.javaxiu.com/37896.html

public class DataSetSaveVO {    //唯一标识符为空    @NotBlank(message = "user uuid is empty")    //用户名称只能是字母和数字    @Pattern(regexp = "^[a-z0-9]+$", message = "user names can only be alphabetic and numeric")    @Length(max = 48, message = "user uuid length over 48 byte")    private String userUuid;    //数据集名称只能是字母和数字    @Pattern(regexp = "^[A-Za-z0-9]+$", message = "data set names can only be letters and Numbers")    //文件名称过长    @Length(max = 48, message = "file name too long")    //文件名称为空    @NotBlank(message = "file name is empty")    private String name;    //数据集描述最多为256字节    @Length(max = 256, message = "data set description length over 256 byte")    //数据集描述为空    @NotBlank(message = "data set description is null")    private String description;}

说明:message字段为不符合校验规则时抛出的异常信息文章源自JAVA秀-https://www.javaxiu.com/37896.html

  • Controller层中的方法文章源自JAVA秀-https://www.javaxiu.com/37896.html

@PostMappingpublic ResponseVO createDataSet(@Valid @RequestBody DataSetSaveVO dataSetVO) {    return ResponseUtil.success(dataSetService.saveDataSet(dataSetVO));}

说明:在校验的实体DataSetSaveVO旁边添加@Valid或@Validated注解文章源自JAVA秀-https://www.javaxiu.com/37896.html

使用commons-lang3

引入依赖文章源自JAVA秀-https://www.javaxiu.com/37896.html

<dependency>    <groupId>org.apache.commons</groupId>    <artifactId>commons-lang3</artifactId>    <version>3.4</version></dependency>

常用方法说明文章源自JAVA秀-https://www.javaxiu.com/37896.html

方法说明
CollectionUtils.isEmpty判断集合是否为空,为null或者size==0,返回true
CollectionUtils.isNotEmpty判断集合是否为非空
StringUtils.isEmpty判断字符串是否为空
StringUtils.isNotEmpty判断字符串是否非空
StringUtils.isBlank判断字符串是否为空,为null或者size==0或者只存在空白字符(如" "),则返回true
StringUtils.isNotBlank判断字符串是否为非空
  • 测试代码文章源自JAVA秀-https://www.javaxiu.com/37896.html

//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(" "));  //falseList<Integer> emptyList = new ArrayList<>();List<Integer> nullList = null;List<Integer> notEmptyList = new ArrayList<>();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));   //true

自定义注解

当上面的方面都无法满足校验的需求以后,可以考虑使用自定义注解。文章源自JAVA秀-https://www.javaxiu.com/37896.html

推荐阅读• Soul网关中利用HTTP长轮询实现数据同步,这也太好用了叭!• 腾讯面试官:如何停止一个正在运行的线程?我蒙了。。。• 你手写过堵塞队列吗?• 你手写过堵塞队列吗?最近面试BATJ,整理一份面试资料《Java面试BAT通关手册》,覆盖了Java核心技术、JVM、Java并发、SSM、微服务、数据库、数据结构等等。获取方式:点“在看”,关注公众号并回复 Java 领取,更多内容陆续奉上。

文章有帮助的话,在看,转发吧。文章源自JAVA秀-https://www.javaxiu.com/37896.html

谢谢支持哟 (*^__^*)文章源自JAVA秀-https://www.javaxiu.com/37896.html

继续阅读
速蛙云 - 极致体验,强烈推荐!!!购买套餐就免费送各大视频网站会员!快速稳定、独家福利社、流媒体稳定解锁!速度快,全球上网、视频、游戏加速、独立IP均支持!基础套餐性价比很高!这里不多说,我一直正在使用,推荐购买:https://www.javaxiu.com/59919.html
weinxin
资源分享QQ群
本站是JAVA秀团队的技术分享社区, 会经常分享资源和教程; 分享的时代, 请别再沉默!
沙海
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定