Springboot hibernate-validator 6.x快速校验示例代码
程序员文章站
2022-03-03 10:49:29
目录一、版本信息及maven依赖二、定义实体bean三、测试controller四、hibernate-validator全局异常处理五、hibernate-validator快速校验一、版本信息及m...
一、版本信息及maven依赖
hibernate-validator 7.x版本有问题,暂时以6.2.1.final为例,6.2.1.final版本解决了log4j版本的漏洞
<properties> <!-- jdk版本 --> <java.version>1.8</java.version> <!-- 构建时编码 --> <project.build.sourceencoding>utf-8</project.build.sourceencoding> <!-- 输出时编码 --> <project.reporting.outputencoding>utf-8</project.reporting.outputencoding> <hutool.version>5.7.16</hutool.version> <hibernate-validator.version>6.2.1.final</hibernate-validator.version> </properties>
记得引入:spring-boot-starter-validation
<dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-validation</artifactid> </dependency> <dependency> <groupid>org.hibernate.validator</groupid> <artifactid>hibernate-validator</artifactid> </dependency> <dependency> <groupid>cn.hutool</groupid> <artifactid>hutool-all</artifactid> <version>${hutool.version}</version> </dependency>
二、定义实体bean
import javax.validation.constraints.email; import javax.validation.constraints.max; import javax.validation.constraints.min; import javax.validation.constraints.notblank; import org.hibernate.validator.constraints.length; public class user { private integer id; @min(18) @max(200) private integer age; @notblank(message = "姓名不能为空") @length(min = 2, max = 6, message = "长度必须在{min}和{max}个字符之间") private string name; @notblank(message = "电子邮箱不能为空") @email(message = "电子邮箱格式不正确") private string email; public integer getid() { return id; } public void setid(integer id) { this.id = id; } public integer getage() { return age; } public void setage(integer age) { this.age = age; } public string getname() { return name; } public void setname(string name) { this.name = name; } public string getemail() { return email; } public void setemail(string email) { this.email = email; } @override public string tostring() { return "user [id=" + id + ", age=" + age + ", name=" + name + ", email=" + email + "]"; } }
三、测试controller
需要在类上面加上注解:@validated
import javax.validation.valid; import javax.validation.constraints.notnull; import org.springframework.validation.annotation.validated; import org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.restcontroller; @restcontroller @validated public class usercontroller { @requestmapping("/get") public user get(@notnull(message = "id不能为空") integer id, @notnull(message = "姓名不能为空") string name) { user user = new user(); user.setname("lisi"); user.setid(id); return user; } @requestmapping("/save") public user get(@valid user user) { return user; } }
四、hibernate-validator全局异常处理
import java.util.list; import java.util.set; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import javax.validation.constraintviolation; import javax.validation.constraintviolationexception; import org.springframework.http.httpstatus; import org.springframework.validation.bindexception; import org.springframework.validation.fielderror; import org.springframework.web.bind.methodargumentnotvalidexception; import org.springframework.web.bind.annotation.controlleradvice; import org.springframework.web.bind.annotation.exceptionhandler; import org.springframework.web.bind.annotation.responsebody; @controlleradvice public class globalexception { public static final string delim = ","; @exceptionhandler(exception.class) @responsebody public string exceptionhandler(httpservletrequest request, httpservletresponse response, exception e) { if(e instanceof constraintviolationexception) { //@requestparam上参数validate失败后抛出的异常 constraintviolationexception cve = (constraintviolationexception) e; set<constraintviolation<?>> violations = cve.getconstraintviolations(); stringbuffer sb = new stringbuffer(""); for (constraintviolation<?> constraintviolation : violations) { sb.append(constraintviolation.getmessage()).append(delim); } if(sb.indexof(delim) > -1) { sb.deletecharat(sb.length() - 1); } system.out.println("constraintviolationexception sb="+sb); response.setstatus(httpstatus.bad_request.value()); return sb.tostring(); }else if(e instanceof bindexception) { //@requestparam上实体对象validate失败后抛出的异常 bindexception be = (bindexception) e; system.out.println("be.getmessage()="+be.getmessage()); list<fielderror> fielderrors = be.getbindingresult().getfielderrors(); stringbuffer sb = new stringbuffer(""); for (fielderror fielderror : fielderrors) { sb.append(fielderror.getdefaultmessage()).append(delim); //system.out.println("fielderror.getdefaultmessage() =" + fielderror.getdefaultmessage()); } if(sb.indexof(delim) > -1) { sb.deletecharat(sb.length() - 1); } system.out.println("bindexception sb="+sb); response.setstatus(httpstatus.bad_request.value()); return sb.tostring(); }else if(e instanceof methodargumentnotvalidexception) { //@requestbody上validate失败后抛出的异常 methodargumentnotvalidexception mave = (methodargumentnotvalidexception) e; system.out.println("mave.getmessage() = " + mave.getmessage()); list<fielderror> fielderrors = mave.getbindingresult().getfielderrors(); stringbuffer sb = new stringbuffer(""); for (fielderror fielderror : fielderrors) { sb.append(fielderror.getdefaultmessage()).append(delim); //system.out.println("fielderror.getdefaultmessage() =" + fielderror.getdefaultmessage()); } if(sb.indexof(delim) > -1) { sb.deletecharat(sb.length() - 1); } system.out.println("methodargumentnotvalidexception sb="+sb); response.setstatus(httpstatus.bad_request.value()); return sb.tostring(); } return "系统异常"; } }
五、hibernate-validator快速校验
hibernate-validator默认会全部校验后再返回所有错误结果,为了让hibernate-validator检查到第一个错误马上返回结果,需要配置快速校验
import javax.validation.validation; import javax.validation.validator; import javax.validation.validatorfactory; import org.hibernate.validator.hibernatevalidator; import org.springframework.boot.autoconfigure.condition.conditionalonmissingbean; import org.springframework.context.annotation.bean; import org.springframework.context.annotation.configuration; import org.springframework.validation.beanvalidation.methodvalidationpostprocessor; @configuration public class validatorconfiguration { /** * 快速返回校验器 * @return */ @bean @conditionalonmissingbean(value = validator.class) public validator validator() { //hibernate-validator 6.x没问题,7.x有问题 validatorfactory validatorfactory = validation.byprovider(hibernatevalidator.class) .configure() .failfast(true) //.addproperty("hibernate.validator.fail_fast", "true") .buildvalidatorfactory(); return validatorfactory.getvalidator(); } /** * 设置快速校验,返回方法校验处理器 * @return */ @bean @conditionalonmissingbean(value = methodvalidationpostprocessor.class) public methodvalidationpostprocessor methodvalidationpostprocessor() { methodvalidationpostprocessor postprocessor = new methodvalidationpostprocessor(); postprocessor.setvalidator(validator()); return postprocessor; } }
到此这篇关于springboot hibernate-validator 6.x校验的文章就介绍到这了,更多相关springboot hibernate validator 校验内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!