第2天:Java验证

Intro

最近,我专注于使用Spring Boot,Java和Swagger构建REST API。 我们都知道REST API涉及其中的Request和Response参数。 我对Java如何提供验证以防止重复的代码行感到惊讶。 在注释时代之前,我们总是使用如果别的指令。 如果此字段为null,则引发异常;如果A为null,则B成为强制性,依此类推。 假设您创建数百个涉及数百个字段参数的API?

Validation annotation

因此,Java为您提供了一个解决方案。 您可以将验证注释附加在字段中。 如果创建自定义验证,则也可以将其放在类级别。 我会记下最基本的一个。 以下是用于请求参数的字段验证的常用注释。

  • @ NotBlank -> validates that value is not null. can be used in any type of field. usually String type
  • @ Size -> validates size/length of value. Usually applied for integer type. It has attribute min and max
  • @ Pattern -> to validate pattern using regex. I used this one a lot. It is very convenience to use other than comparing String with equals method. The challenge is creating the regex itself. You can simulate it here before use it. Probably I will write about this part in separate post.

Custom Validation

If your requirement getting complicated, and no basic annotation can accommodate it, you may create your own validation. This post is a good start .
I will share one of my custom validation later :D

Some example

@Pattern(regexp="^[0-9]*$")
@NotBlank
@Size(max = 20)
String myNumber;

@MyCustomValidation
String myCode;

from: https://dev.to//ninankara/day-2-java-validation-2fgc

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值