SpringBoot集成Validation参数校验
程序员文章站
2022-06-23 13:12:10
本文实例为大家分享了springboot集成validation参数校验的具体代码,供大家参考,具体内容如下1、依赖springboot在web启动器中已经包含validator包
本文实例为大家分享了springboot集成validation参数校验的具体代码,供大家参考,具体内容如下
1、依赖
springboot在web启动器中已经包含validator包
<dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-web</artifactid> </dependency>
非springboot项目,需要自定引入依赖
<dependency> <groupid>org.hibernate.validator</groupid> <artifactid>hibernate-validator</artifactid> <version>6.1.5.final</version> </dependency> <dependency> <groupod>org.glassfish</groupid> <artifactid>jakarta.el</artifactid> <version>3.0.3</version> </dependency>
2、常用约束说明
package com.smile.project.validator.utils; public class 常用约束说明 { /** * @null:元素为null * @notnull:元素不为null * @asserttrue:元素为true * @assertfalse:元素为false * @min(value):数字的值大于等于指定的最小值 * @max(value):数字的值小于等于指定的最大值 * @decimalmin(value):大数值大于等于指定的最小值 * @decimalmax(value):大数值小于等于指定的最大值 * @size(max=,min=):元素的大小在指定的范围内 * @digits(integer,fraction):元素是一个数字,其值必须在可接受的范围内 * @past:一个过去的日期 * @future:一个将来的日期 * @pattern(regex=,flag=):指定的正则表达式 * @url:必须是一个url * @email:必须是email格式 * @notblank:字符串不能为空 * @notempty:集合不能为空 * @length:长度必须在指定范围内 * @valid:对实体类进行校验 */ }
3、实体约束示例
import com.smile.project.validator.utils.gender; import lombok.data; import javax.validation.constraints.email; import javax.validation.constraints.notnull; import javax.validation.constraints.size; @data public class sysuser { private long id; @notnull(message = "用户名不能为空") @size(min = 3,max = 5,message = "用户名长度为{min}-{max}之间") private string username; @notnull(message = "昵称不能为空") private string name; @notnull(message = "密码不能为空") private string password; @email(message = "邮箱格式不合法") private string email; private string gender; }
4、控制层示例
需要在class加上@validated注解
如果参数时实体,需要加上@valid注解
import com.smile.project.validator.entity.sysuser; import org.springframework.http.responseentity; import org.springframework.validation.annotation.validated; import org.springframework.web.bind.annotation.getmapping; import org.springframework.web.bind.annotation.postmapping; import org.springframework.web.bind.annotation.restcontroller; import javax.validation.valid; import javax.validation.constraints.notnull; @restcontroller @validated public class sysusercontroller { /** * 方法参数为实体校验 */ @postmapping("/register") public responseentity register(@valid sysuser sysuser){ return responseentity.ok(sysuser); } /** * 方法参数校验 */ @getmapping("user") public responseentity getuser(@notnull(message = "用户名不能为空") string username){ sysuser sysuser = new sysuser(); sysuser.setname("smile"); return responseentity.ok(sysuser); } }
5、异常捕获
全局异常捕获,当出现参数校验不合法时捕获异常,并且返回给前端
import org.springframework.http.responseentity; import org.springframework.validation.fielderror; import org.springframework.validation.objecterror; 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; import javax.validation.constraintviolation; import javax.validation.constraintviolationexception; import java.util.hashmap; import java.util.list; import java.util.set; /** * 全局异常捕获 * 当出翔参数校验不合法时捕获异常,并且返回给前端 */ @controlleradvice public class globhandler { /** * 捕获方法参数校验异常 */ @exceptionhandler(constraintviolationexception.class) @responsebody public responseentity constraintviolationexceptionhandler(constraintviolationexception e){ set<constraintviolation<?>> message = e.getconstraintviolations(); hashmap<string,object> map = new hashmap<>(); message.stream().foreach(msg ->{ string path = msg.getpropertypath().tostring(); string field = path.substring(path.indexof(".")+1); map.put(field,msg.getmessagetemplate()); }); return responseentity.ok(map); } /** * 捕获实体参数校验异常 */ @exceptionhandler(methodargumentnotvalidexception.class) @responsebody public responseentity resolvemethodargumentnotvalidexception(methodargumentnotvalidexception e){ list<objecterror> allerrors = e.getbindingresult().getallerrors(); hashmap<string,object> map = new hashmap<>(); allerrors.stream().foreach(error -> { fielderror fielderror = (fielderror) error; map.put(fielderror.getfield(),fielderror.getdefaultmessage()); }); return responseentity.ok(map); } }
6、自定义校验规则
特殊的字段需要自定义规则,比如身份证号码,邮箱,电话等
6.1、定义校验注解
import com.smile.project.validator.utils.gendervalidator; import javax.validation.constraint; import javax.validation.payload; import java.lang.annotation.*; import static java.lang.annotation.elementtype.field; import static java.lang.annotation.elementtype.method; import static java.lang.annotation.retentionpolicy.runtime; /** * 定义校验注解 */ @target({method,field}) @retention(runtime) @constraint(validatedby = gendervalidator.class) @documented public @interface gender { string message() default "性别为男或者女"; class<?>[] groups() default {}; class<? extends payload[]>[] payload() default {}; }
6.2、gendervalidator实现constraintvalidator接口并提供校验规则
import javax.validation.constraintvalidator; import javax.validation.constraintvalidatorcontext; /** * 实现constraintvalidator接口并提供校验规则 */ public class gendervalidator implements constraintvalidator<gender,string> { //初始化校验值 @override public void initialize(gender constraintannotation) { } //检验规则 @override public boolean isvalid(string value, constraintvalidatorcontext content) { return "男".equals(value) || "女".equals(value); } }
6.3、在成员变量中使用注解
import com.smile.project.validator.utils.gender; import lombok.data; import javax.validation.constraints.email; import javax.validation.constraints.notnull; import javax.validation.constraints.size; @data public class sysuser { private long id; @notnull(message = "用户名不能为空") @size(min = 3,max = 5,message = "用户名长度为{min}-{max}之间") private string username; @notnull(message = "昵称不能为空") private string name; @notnull(message = "密码不能为空") private string password; @email(message = "邮箱格式不合法") private string email; @gender() private string gender; }
7、分组校验
默认情况下,不指定分组都属于默认组;使用分组校验有利于分层校验开发
7.1、新建两个接口,一个用于查询,一个用于添加
public interface add extends default { } public interface select extends default { }
7.2、修改尸体校验规则,如果不指定分组默认时default组;
import com.smile.project.validator.utils.gender; import lombok.data; import javax.validation.constraints.email; import javax.validation.constraints.notnull; import javax.validation.constraints.size; @data public class sysuser { private long id; @notnull(message = "用户名不能为空",groups = add.class) @size(min = 3,max = 5,message = "用户名长度为{min}-{max}之间") private string username; @notnull(message = "昵称不能为空",groups = select.class) private string name; @notnull(message = "密码不能为空",groups = add.class) private string password; @email(message = "邮箱格式不合法",groups = select.class) private string email; @gender() private string gender; }
7.3、控制层示例,此时只会校验add组和default组
//分组校验 @postmapping("/user") public responseentity adduser(@validated(value = add.class) @requestbody sysuser sysuser){ return responseentity.ok(sysuser); }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
推荐阅读
-
Springboot 使用@Valid+BindingResult进行controller层接口参数校验
-
springboot使用hibernate validator校验,Bean Validation校验
-
SpringBoot参数校验的方法总结
-
SpringBoot使用validation-api实现对枚举类参数校验的方法
-
springboot使用校验框架validation校验的示例
-
springboot 单个参数校验
-
springboot 单个参数校验
-
如何使用Spring Validation优雅地校验参数
-
SpringBoot @Validated注解实现参数分组校验的方法实例
-
Springboot参数校验--最全