前言

接触springboot一年多,是时候摆脱这种校验方式了233 ,每个参数都if判断,一眼看过去就是很low的程序员。

validation有了这个插件就再也不用这样去校验参数了,可以让我们在项目中不用浪费很多时间在参数校验这里,从而更专注于业务逻辑

正文

首先引入依赖

 <dependency>
  <groupid>org.springframework.boot</groupid>
  <artifactid>spring-boot-starter-web</artifactid>
 </dependency>

这里创建一个用户的dto对象

@data
@apimodel("用户-表单对象")
public class sportsusercreatform{
 
 @apimodelproperty(value="用户唯一标识",example = "0")
 @notnull(groups = {update.class})
 private long id;
 
 @apimodelproperty(value = "所属机构唯一标识(冗余字段)", example = "0")
 private long organizationid;
 
 @apimodelproperty("登录用户名")
 @notblank(message = "用户名不能为空")
 @length(max = 10, message = "用户名最长为10位")
 private string loginname;
 
 @apimodelproperty("密码")
 private string password;
 
 @apimodelproperty("手机号")
 private string phone;
 
 @apimodelproperty("邮箱")
 private string email;
 
 @apimodelproperty("性别( 'male', 'female' )")
 @notnull(message = "用户性别不能为空")
 private sportsuserenumgender gander;
 
 @apimodelproperty(value = "出生日期-13位时间戳",example = "0")
 private long birthday;
 
 @apimodelproperty("身份证号")
 private string idnumber;
 
 @apimodelproperty("用户昵称")
 private string nickname;
 
}

在controller层添加@validated注解,添加注解之后spring就会逐个校验dto中加了校验注解的字段,完全通过才可以进入业务处理,否则就会抛出methodargumentnotvalidexception异常

 @postmapping("user/add")
 @requiresauthentication
 @apioperation("添加用户")
 public sportsuser adduser(@validated @requestbody sportsusercreatform user) throws exception{
 return userbiz.adduser(user);
 }

一般项目来说抛出异常都会有约定好的json格式返回错误码和错误信息,如果不处理就无法按照约定格式返回。这里我们可以通过声明全局异常处理类来拦截异常并将异常处理成前端能操作的json数据。(这里只需要关注methodargumentnotvalidexception异常)

@slf4j
@order(ordered.highest_precedence)
@restcontrolleradvice
public class globalexceptionadvice {
 
 @exceptionhandler(methodargumentnotvalidexception.class)
 @responsebody
 public responseentity<object> handlebeanvalidation(httpservletresponse res, methodargumentnotvalidexception e) throws exception{
 res.setstatus(httpstatus.ok.value());
 list<objecterror> errors = e.getbindingresult().getallerrors();
 objecterror error = errors.get(0);// 如果有多个异常,这里只取第一个异常。没有必要把所有异常都抛出(错就是错,第一个校验都没通过,自然也轮不到第二个校验。)
 string json = jsonutils.obj2json(error);
 map map = jsonutils.json2map(json);
 okmessage result = new okmessage();
 result.setmsg("请求参数错误"e.getbindingresult().getfielderror().getdefaultmessage() + "]");
 result.setcode("param-000001");
 return new responseentity<>(result, httpstatus.ok);
 }
}

分组校验

有的人就要发问了,”啊,你这校验不行啊,我在添加的时候id是自动生成的不需要校验,编辑的时候就需要校验id了,我是不是要建两个一模一样的dto,这样岂不是显得我很憨?!这不是增加无用代码吗?差评!”

 其实不然,在此我们可以用到 groups 属性来解决此场景下的问题。

声明分组

注意:在声明分组的时候尽量继承 extend javax.validation.groups.default。 否则,在你声明@validated(update.class)的时候,就会出现你在默认没添加groups = {}的时候的校验组@email(message = “邮箱格式不对”)不会自动校验,因为默认的校验组是groups = {default.class}。

 
import javax.validation.groups.default;
 
/**
 * 数据新增分组
 */
public interface create extends default {
 
}
 
import javax.validation.groups.default;
 
/**
 * 数据更新分组
 */
public interface update extends default {
 
}

修改controller中的@validated注解,声明校验分组(下面用的是create.class所以并不会校验id)

 @postmapping("user/add")
 @requiresauthentication
 @apioperation("添加用户")
 public sportsuser adduser(@validated(create.class) @requestbody sportsusercreatform user) throws exception{
 return userbiz.adduser(user);
 }

下面附上注解说明

验证注解 验证的数据类型 说明
@assertfalse boolean,boolean 验证注解的元素值是false
@asserttrue boolean,boolean 验证注解的元素值是true
@notnull 任意类型 验证注解的元素值不是null
@null 任意类型 验证注解的元素值是null
@min(value=值) bigdecimal,biginteger, byte,short, int, long,等任何number或charsequence(存储的是数字)子类型 验证注解的元素值大于等于@min指定的value值
@max(value=值) 和@min要求一样 验证注解的元素值小于等于@max指定的value值
@decimalmin(value=值) 和@min要求一样 验证注解的元素值大于等于@ decimalmin指定的value值
@decimalmax(value=值) 和@min要求一样 验证注解的元素值小于等于@ decimalmax指定的value值
@digits(integer=整数位数, fraction=小数位数) 和@min要求一样 验证注解的元素值的整数位数和小数位数上限
@size(min=下限, max=上限) 字符串、collection、map、数组等 验证注解的元素值的在min和max(包含)指定区间之内,如字符长度、集合大小
@past java.util.date,java.util.calendar;joda time类库的日期类型 验证注解的元素值(日期类型)比当前时间早
@future 与@past要求一样 验证注解的元素值(日期类型)比当前时间晚
@notblank charsequence子类型 验证注解的元素值不为空(不为null、去除首位空格后长度为0),不同于@notempty,@notblank只应用于字符串且在比较时会去除字符串的首位空格
@length(min=下限, max=上限) charsequence子类型 验证注解的元素值长度在min和max区间内
@notempty charsequence子类型、collection、map、数组 验证注解的元素值不为null且不为空(字符串长度不为0、集合大小不为0)
@range(min=最小值, max=最大值) bigdecimal,biginteger,charsequence, byte, short, int, long等原子类型和包装类型 验证注解的元素值在最小值和最大值之间
@email(regexp=正则表达式,flag=标志的模式) charsequence子类型(如string) 验证注解的元素值是email,也可以通过regexp和flag指定自定义的email格式
@pattern(regexp=正则表达式,flag=标志的模式) string,任何charsequence的子类型 验证注解的元素值与指定的正则表达式匹配
@valid 任何非原子类型 指定递归验证关联的对象如用户对象中有个地址对象属性,如果想在验证用户对象时一起验证地址对象的话,在地址对象上加@valid注解即可

此处只列出hibernate validator提供的大部分验证约束注解,请参考hibernate validator官方文档了解其他验证约束注解和进行自定义的验证约束注解定义。

常用的几个:
1.@notnull:不能为null,但可以为empty(""," ","   ")
2.@notempty:不能为null,而且长度必须大于0 (" ","  ")
3.@notblank:只能作用在string上,不能为null,而且调用trim()后,长度必须大于0("test")    即:必须有实际字符

总结

到此这篇关于spring boot validation校验的文章就介绍到这了,更多相关springboot validation校验内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!