摘要:本文首先阐述了jsr303规范与hibernate validator的关系,以及spring boot项目中如何引入校验依赖。重点讲解了两种参数校验方式:requestbody参数校验(使用@validated注解dto对象)和requestparam/pathvariable校验(需在controller类上加@validated)。文章详细展示了分组校验、嵌套校验、集合校验等进阶功能,并提供了自定义校验注解的实现方法。最后剖析了校验
1、简单使用
java api规范(jsr303)定义了bean校验的标准validation-api,但没有提供实现。hibernate validation是对这个规范的实现,并增加了校验注解如@email、@length等。
spring validation是对hibernate validation的二次封装,用于支持spring mvc参数自动校验。接下来,我们以spring-boot项目为例,介绍spring validation的使用。
引入依赖
如果spring-boot版本小于2.3.x,spring-boot-starter-web会自动传入hibernate-validator依赖。如果spring-boot版本大于2.3.x,则需要手动引入依赖:
<dependency>
<groupid>org.hibernate</groupid>
<artifactid>hibernate-validator</artifactid>
<version>6.0.1.final</version>
</dependency>
对于web服务来说,为防止非法参数对业务造成影响,在controller层一定要做参数校验的!大部分情况下,请求参数分为如下两种形式:
- post、put请求,使用requestbody传递参数;
- get请求,使用requestparam/pathvariable传递参数。
下面我们简单介绍下requestbody和requestparam/pathvariable的参数校验实战!
requestbody参数校验
post、put请求一般会使用requestbody传递参数,这种情况下,后端使用dto对象进行接收。只要给dto对象加上@validated注解就能实现自动参数校验。比如,有一个保存user的接口,要求username长度是2-10,account和password字段长度是6-20。
如果校验失败,会抛出methodargumentnotvalidexception异常,spring默认会将其转为400(bad request)请求。
dto表示数据传输对象(data transfer object),用于服务器和客户端之间交互传输使用的。在spring-web项目中可以表示用于接收请求参数的bean对象。
在dto字段上声明约束注解
@data
publicclass userdto {
private long userid;
@notnull
@length(min = 2, max = 10)
private string username;
@notnull
@length(min = 6, max = 20)
private string account;
@notnull
@length(min = 6, max = 20)
private string password;
}
在方法参数上声明校验注解
@postmapping("/save")
public result saveuser(@requestbody @validated userdto userdto) {
// 校验通过,才会执行业务逻辑处理
return result.ok();
}
这种情况下,使用@valid和@validated都可以。
requestparam/pathvariable参数校验
get请求一般会使用requestparam/pathvariable传参。如果参数比较多(比如超过6个),还是推荐使用dto对象接收。
否则,推荐将一个个参数平铺到方法入参中。在这种情况下,必须在controller类上标注@validated注解,并在入参上声明约束注解(如@min等)。如果校验失败,会抛出constraintviolationexception异常。
代码示例如下:
@requestmapping("/api/user")
@restcontroller
@validated
publicclass usercontroller {
// 路径变量
@getmapping("{userid}")
public result detail(@pathvariable("userid") @min(10000000000000000l) long userid) {
// 校验通过,才会执行业务逻辑处理
userdto userdto = new userdto();
userdto.setuserid(userid);
userdto.setaccount("11111111111111111");
userdto.setusername("xixi");
userdto.setaccount("11111111111111111");
return result.ok(userdto);
}
// 查询参数
@getmapping("getbyaccount")
public result getbyaccount(@length(min = 6, max = 20) @notnull string account) {
// 校验通过,才会执行业务逻辑处理
userdto userdto = new userdto();
userdto.setuserid(10000000000000003l);
userdto.setaccount(account);
userdto.setusername("xixi");
userdto.setaccount("11111111111111111");
return result.ok(userdto);
}
}
统一异常处理
前面说过,如果校验失败,会抛出methodargumentnotvalidexception或者constraintviolationexception异常。在实际项目开发中,通常会用统一异常处理来返回一个更友好的提示。
比如我们系统要求无论发送什么异常,http的状态码必须返回200,由业务码去区分系统的异常情况。
@restcontrolleradvice
publicclass commonexceptionhandler {
@exceptionhandler({methodargumentnotvalidexception.class})
@responsestatus(httpstatus.ok)
@responsebody
public result handlemethodargumentnotvalidexception(methodargumentnotvalidexception ex) {
bindingresult bindingresult = ex.getbindingresult();
stringbuilder sb = new stringbuilder("校验失败:");
for (fielderror fielderror : bindingresult.getfielderrors()) {
sb.append(fielderror.getfield()).append(":").append(fielderror.getdefaultmessage()).append(", ");
}
string msg = sb.tostring();
return result.fail(businesscode.参数校验失败, msg);
}
@exceptionhandler({constraintviolationexception.class})
@responsestatus(httpstatus.ok)
@responsebody
public result handleconstraintviolationexception(constraintviolationexception ex) {
return result.fail(businesscode.参数校验失败, ex.getmessage());
}
}
2、进阶使用
分组校验
在实际项目中,可能多个方法需要使用同一个dto类来接收参数,而不同方法的校验规则很可能是不一样的。这个时候,简单地在dto类的字段上加约束注解无法解决这个问题。因此,spring-validation支持了分组校验的功能,专门用来解决这类问题。
还是上面的例子,比如保存user的时候,userid是可空的,但是更新user的时候,userid的值必须>=10000000000000000l;其它字段的校验规则在两种情况下一样。这个时候使用分组校验的代码示例如下:
约束注解上声明适用的分组信息groups
@data
publicclass userdto {
@min(value = 10000000000000000l, groups = update.class)
private long userid;
@notnull(groups = {save.class, update.class})
@length(min = 2, max = 10, groups = {save.class, update.class})
private string username;
@notnull(groups = {save.class, update.class})
@length(min = 6, max = 20, groups = {save.class, update.class})
private string account;
@notnull(groups = {save.class, update.class})
@length(min = 6, max = 20, groups = {save.class, update.class})
private string password;
/**
* 保存的时候校验分组
*/
publicinterface save {
}
/**
* 更新的时候校验分组
*/
publicinterface update {
}
}
@validated注解上指定校验分组
@postmapping("/save")
public result saveuser(@requestbody @validated(userdto.save.class) userdto userdto) {
// 校验通过,才会执行业务逻辑处理
return result.ok();
}
@postmapping("/update")
public result updateuser(@requestbody @validated(userdto.update.class) userdto userdto) {
// 校验通过,才会执行业务逻辑处理
return result.ok();
}
嵌套校验
前面的示例中,dto类里面的字段都是基本数据类型和string类型。但是实际场景中,有可能某个字段也是一个对象,这种情况先,可以使用嵌套校验。
比如,上面保存user信息的时候同时还带有job信息。需要注意的是,此时dto类的对应字段必须标记@valid注解。
@data
publicclass userdto {
@min(value = 10000000000000000l, groups = update.class)
private long userid;
@notnull(groups = {save.class, update.class})
@length(min = 2, max = 10, groups = {save.class, update.class})
private string username;
@notnull(groups = {save.class, update.class})
@length(min = 6, max = 20, groups = {save.class, update.class})
private string account;
@notnull(groups = {save.class, update.class})
@length(min = 6, max = 20, groups = {save.class, update.class})
private string password;
@notnull(groups = {save.class, update.class})
@valid
private job job;
@data
publicstaticclass job {
@min(value = 1, groups = update.class)
private long jobid;
@notnull(groups = {save.class, update.class})
@length(min = 2, max = 10, groups = {save.class, update.class})
private string jobname;
@notnull(groups = {save.class, update.class})
@length(min = 2, max = 10, groups = {save.class, update.class})
private string position;
}
/**
* 保存的时候校验分组
*/
publicinterface save {
}
/**
* 更新的时候校验分组
*/
publicinterface update {
}
}
嵌套校验可以结合分组校验一起使用。还有就是嵌套集合校验会对集合里面的每一项都进行校验,例如list<job>字段会对这个list里面的每一个job对象都进行校验
集合校验
如果请求体直接传递了json数组给后台,并希望对数组中的每一项都进行参数校验。此时,如果我们直接使用java.util.collection下的list或者set来接收数据,参数校验并不会生效!我们可以使用自定义list集合来接收参数:
包装list类型,并声明@valid注解
public class validationlist<e> implements list<e> {
@delegate // @delegate是lombok注解
@valid // 一定要加@valid注解
public list<e> list = new arraylist<>();
// 一定要记得重写tostring方法
@override
public string tostring() {
return list.tostring();
}
}
@delegate注解受lombok版本限制,1.18.6以上版本可支持。如果校验不通过,会抛出notreadablepropertyexception,同样可以使用统一异常进行处理。
比如,我们需要一次性保存多个user对象,controller层的方法可以这么写:
@postmapping("/savelist")
public result savelist(@requestbody @validated(userdto.save.class) validationlist<userdto> userlist) {
// 校验通过,才会执行业务逻辑处理
return result.ok();
}
自定义校验
业务需求总是比框架提供的这些简单校验要复杂的多,我们可以自定义校验来满足我们的需求。
自定义spring validation非常简单,假设我们自定义加密id(由数字或者a-f的字母组成,32-256长度)校验,主要分为两步:
自定义约束注解
@target({method, field, annotation_type, constructor, parameter})
@retention(runtime)
@documented
@constraint(validatedby = {encryptidvalidator.class})
public @interface encryptid {
// 默认错误消息
string message() default "加密id格式错误";
// 分组
class<?>[] groups() default {};
// 负载
class<? extends payload>[] payload() default {};
}
实现constraintvalidator接口编写约束校验器
public class encryptidvalidator implements constraintvalidator<encryptid, string> {
privatestaticfinal pattern pattern = pattern.compile("^[a-f\\d]{32,256}$");
@override
public boolean isvalid(string value, constraintvalidatorcontext context) {
// 不为null才进行校验
if (value != null) {
matcher matcher = pattern.matcher(value);
return matcher.find();
}
returntrue;
}
}
这样我们就可以使用@encryptid进行参数校验了!
编程式校验
上面的示例都是基于注解来实现自动校验的,在某些情况下,我们可能希望以编程方式调用验证。这个时候可以注入javax.validation.validator对象,然后再调用其api。
@autowired
private javax.validation.validator globalvalidator;
// 编程式校验
@postmapping("/savewithcodingvalidate")
public result savewithcodingvalidate(@requestbody userdto userdto) {
set<constraintviolation<userdto>> validate = globalvalidator.validate(userdto, userdto.save.class);
// 如果校验通过,validate为空;否则,validate包含未校验通过项
if (validate.isempty()) {
// 校验通过,才会执行业务逻辑处理
} else {
for (constraintviolation<userdto> userdtoconstraintviolation : validate) {
// 校验失败,做其它逻辑
system.out.println(userdtoconstraintviolation);
}
}
return result.ok();
}
快速失败(fail fast)
spring validation默认会校验完所有字段,然后才抛出异常。可以通过一些简单的配置,开启fali fast模式,一旦校验失败就立即返回。
@bean
public validator validator() {
validatorfactory validatorfactory = validation.byprovider(hibernatevalidator.class)
.configure()
// 快速失败模式
.failfast(true)
.buildvalidatorfactory();
return validatorfactory.getvalidator();
}
@valid和@validated区别

3、实现原理
requestbody参数校验实现原理
在spring-mvc中,requestresponsebodymethodprocessor是用于解析@requestbody标注的参数以及处理@responsebody标注方法的返回值的。显然,执行参数校验的逻辑肯定就在解析参数的方法resolveargument()中:
public class requestresponsebodymethodprocessor extends abstractmessageconvertermethodprocessor {
@override
public object resolveargument(methodparameter parameter, @nullable modelandviewcontainer mavcontainer,
nativewebrequest webrequest, @nullable webdatabinderfactory binderfactory) throws exception {
parameter = parameter.nestedifoptional();
//将请求数据封装到dto对象中
object arg = readwithmessageconverters(webrequest, parameter, parameter.getnestedgenericparametertype());
string name = conventions.getvariablenameforparameter(parameter);
if (binderfactory != null) {
webdatabinder binder = binderfactory.createbinder(webrequest, arg, name);
if (arg != null) {
// 执行数据校验
validateifapplicable(binder, parameter);
if (binder.getbindingresult().haserrors() && isbindexceptionrequired(binder, parameter)) {
thrownew methodargumentnotvalidexception(parameter, binder.getbindingresult());
}
}
if (mavcontainer != null) {
mavcontainer.addattribute(bindingresult.model_key_prefix + name, binder.getbindingresult());
}
}
return adaptargumentifnecessary(arg, parameter);
}
}
可以看到,resolveargument()调用了validateifapplicable()进行参数校验。
protected void validateifapplicable(webdatabinder binder, methodparameter parameter) {
// 获取参数注解,比如@requestbody、@valid、@validated
annotation[] annotations = parameter.getparameterannotations();
for (annotation ann : annotations) {
// 先尝试获取@validated注解
validated validatedann = annotationutils.getannotation(ann, validated.class);
//如果直接标注了@validated,那么直接开启校验。
//如果没有,那么判断参数前是否有valid起头的注解。
if (validatedann != null || ann.annotationtype().getsimplename().startswith("valid")) {
object hints = (validatedann != null ? validatedann.value() : annotationutils.getvalue(ann));
object[] validationhints = (hints instanceof object[] ? (object[]) hints : new object[] {hints});
//执行校验
binder.validate(validationhints);
break;
}
}
}
看到这里,大家应该能明白为什么这种场景下@validated、@valid两个注解可以混用。我们接下来继续看webdatabinder.validate()实现。
@override
public void validate(object target, errors errors, object... validationhints) {
if (this.targetvalidator != null) {
processconstraintviolations(
//此处调用hibernate validator执行真正的校验
this.targetvalidator.validate(target, asvalidationgroups(validationhints)), errors);
}
}
最终发现底层最终还是调用了hibernate validator进行真正的校验处理。
方法级别的参数校验实现原理
上面提到的将参数一个个平铺到方法参数中,然后在每个参数前面声明约束注解的校验方式,就是方法级别的参数校验。
实际上,这种方式可用于任何spring bean的方法上,比如controller/service等。其底层实现原理就是aop,具体来说是通过methodvalidationpostprocessor动态注册aop切面,然后使用methodvalidationinterceptor对切点方法织入增强。
public class methodvalidationpostprocessor extends abstractbeanfactoryawareadvisingpostprocessorimplements initializingbean {
@override
public void afterpropertiesset() {
//为所有`@validated`标注的bean创建切面
pointcut pointcut = new annotationmatchingpointcut(this.validatedannotationtype, true);
//创建advisor进行增强
this.advisor = new defaultpointcutadvisor(pointcut, createmethodvalidationadvice(this.validator));
}
//创建advice,本质就是一个方法拦截器
protected advice createmethodvalidationadvice(@nullable validator validator) {
return (validator != null ? new methodvalidationinterceptor(validator) : new methodvalidationinterceptor());
}
}
接着看一下methodvalidationinterceptor:
public class methodvalidationinterceptor implements methodinterceptor {
@override
public object invoke(methodinvocation invocation) throws throwable {
//无需增强的方法,直接跳过
if (isfactorybeanmetadatamethod(invocation.getmethod())) {
return invocation.proceed();
}
//获取分组信息
class<?>[] groups = determinevalidationgroups(invocation);
executablevalidator execval = this.validator.forexecutables();
method methodtovalidate = invocation.getmethod();
set<constraintviolation<object>> result;
try {
//方法入参校验,最终还是委托给hibernate validator来校验
result = execval.validateparameters(
invocation.getthis(), methodtovalidate, invocation.getarguments(), groups);
}
catch (illegalargumentexception ex) {
...
}
//有异常直接抛出
if (!result.isempty()) {
thrownew constraintviolationexception(result);
}
//真正的方法调用
object returnvalue = invocation.proceed();
//对返回值做校验,最终还是委托给hibernate validator来校验
result = execval.validatereturnvalue(invocation.getthis(), methodtovalidate, returnvalue, groups);
//有异常直接抛出
if (!result.isempty()) {
thrownew constraintviolationexception(result);
}
return returnvalue;
}
}
实际上,不管是requestbody参数校验还是方法级别的校验,最终都是调用hibernate validator执行校验,spring validation只是做了一层封装。
到此这篇关于浅析spring validation参数校验的实现原理与进阶用法的文章就介绍到这了,更多相关spring validation参数校验内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论