当前位置:网站首页>大量if else判断如何优化?@Valib详解
大量if else判断如何优化?@Valib详解
2022-07-26 11:46:00 【用户9919783】
1、业务场景
@RequestMapping("/insert")
public String insert(Student student){
if(Objects.equals(student.getName(),"")){
return "姓名不能为空";
}
if(null == student.getAge()){
return "年龄不能为空";
}
return "success";
}如图所示,当前端访问接口时,现在要求参数不能为空,那我们只能这样写两个if判断是否为null。若name访问为空时候,则会如图返回
目前现在只有两个字段,若有大量的字段需要判断则如何呢,写大量的if?当一个接口里无效业务代码量过多,设计是有问题的,而且作为一个优秀的程序员,这不是我们想看到的结果。
如何解决呢?答案是@Valid注解
从代码里可以看到,首先接收的bean对象需要用@valid注解验证,之后需要注意的是,bean里面
数字类型用@NotNull注解,字符串类型用@NotBlank注解,集合类型用的是@NotEmpty判断是否存在。他们判断长度的注解也不同,分别是@Length,@Range,@Size。
注意:这里完成之后,此刻【并不会】返回前端并且提示什么字段为空,还需要在接口加BindingResult参数,接收异常数据,返回空字段给前端。
边栏推荐
- 【安徽大学】考研初试复试资料分享
- 。。。。。。
- Application scheme of ankerui residual pressure monitoring system in residential quarter
- Meiker Studio - Huawei 14 day Hongmeng equipment development practical notes 8
- Data center construction (II): brief introduction to data center
- 武林头条-建站小能手争霸赛
- MongoDN数据库以URL形式连接
- 数据库组成索引和约束
- Li Kai: the interesting and cutting-edge audio and video industry has always attracted me
- Didi was fined 8billion! The era of making money from user data is over
猜你喜欢

。。。。。。

Yuancosmos daily | yuancosmos social app "Party Island" product off the shelves; Guangzhou Nansha yuanuniverse industrial agglomeration zone was unveiled; The inter ministerial joint conference system

Swagger2.9.2 tutorial and swagger3.0.0 tutorial

Some practical, commonly used and increasingly efficient kubernetes aliases

音视频+

Test cases should never be used casually, recording the thinking caused by the exception of a test case

Understanding useref is enough

Wulin headlines - station building expert competition

Sword finger offer 25. merge two sorted linked lists

开放原子开源基金会OpenHarmony工作委员会主席侯培新寄语OpenAtom OpenHarmony分论坛
随机推荐
Sunflower senior product director technology sharing: how to apply in AD domain environment
[countdown 10 days] Tencent cloud audio and video special is about to meet, and the thousand yuan prize is waiting for you!
On the construction and management of low code technology in logistics transportation platform
Wulin headlines - station building expert competition
Query advanced alias
Redis database, which can be understood by zero foundation Xiaobai, is easy to learn and use!
Live broadcast preview at 19:30 on July 27: harmonyos3 and Huawei's full scene new product launch
Is it easy to find a job after programmer training?
GA-RPN:引导锚点的建议区域网络
3.1 创建菜单与游戏页面——上
Query summary of SQL Server
X 2 earn must rely on Ponzi startup? Where is the way out for gamefi? (top)
Data center construction (II): brief introduction to data center
pytest接口自动化测试框架 | 使用装饰器修饰需要运行的用例
Big view +500 cases, software teams should improve R & D efficiency in this way!
MILA旗下初创企业Ubenwa获得250万美元投资,研究婴儿健康AI诊断
What is per title encoding?
Talking about web vitals
【附下载】一款强大的Web自动化漏洞扫描工具——Xray
Exploration on cache design optimization of community like business