欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringBoot使用validation-api实现对枚举类参数校验的方法

程序员文章站 2022-08-08 07:54:22
前言之前写了一个博客是关于使用springboot使用validation-api实现参数校验,当时使用的注解都是validation-api自带的注解只能完成对空值、长度等简单的校验,在我们日常的使...

前言

之前写了一个博客是关于使用springboot使用validation-api实现参数校验,当时使用的注解都是validation-api自带的注解只能完成对空值、长度等简单的校验,在我们日常的使用当中会遇到对参数是否在枚举值类的校验,针对这种情况我们怎么来实现呢?

springboot使用validation-api实现参数校验可参考我的博客:springboot使用validation-api实现参数校验

正文

springboot使用validation-api实现对枚举类参数校验

validationapi框架就是用来解决参数校验中代码冗余问题,validationapi框架提供一些注解用来帮助我们对请求参数进行校验。

maven依赖

<!--参数校验-->
<dependency>
 <groupid>javax.validation</groupid>
 <artifactid>validation-api</artifactid>
 <version>2.0.1.final</version>
</dependency>


<!--提供一些字符串操作-->
<dependency>
 <groupid>org.apache.commons</groupid>
 <artifactid>commons-lang3</artifactid>
 <version>3.3.2</version>
</dependency>


<!--lombok-->
<dependency>
 <groupid>org.projectlombok</groupid>
 <artifactid>lombok</artifactid>
 <version>1.18.2</version>
 <optional>true</optional>
</dependency>


<!--knife4j接口-->
<dependency>
 <groupid>com.github.xiaoymin</groupid>
 <artifactid>knife4j-spring-boot-starter</artifactid>
 <version>2.0.4</version>
</dependency>

enumvalidate:用于对枚举校验的接口

/**
* 用于实现枚举类的校验
*/
public interface enumvalidate<t> {

 /**
  * 校验枚举值是否存在
  */
 boolean existvalidate(t value);
}

actiontypeenumvalid:用于对枚举类校验的自定义注解

@target({elementtype.field, elementtype.method, elementtype.annotation_type})
@retention(retentionpolicy.runtime)
@constraint(validatedby = {actiontypeenumvalidator.class})
@documented
public @interface actiontypeenumvalid {

 string message() default "";


 class<?>[] groups() default {};


 class<? extends payload>[] payload() default {};


 class<?>[] target() default {};

 /**
  * 允许的枚举
  *
  * @return
  */
 class<? extends enum<?>> enumclass();
}

actiontypeenumvalidator:枚举校验器

/**
* 用于校验actiontypeenumvalidator
*/
public class actiontypeenumvalidator implements constraintvalidator<actiontypeenumvalid,string> {


 private class<? extends enum> enumclass;


 @override
 public void initialize(actiontypeenumvalid actiontypeenumvalid) {
  enumclass = actiontypeenumvalid.enumclass();
 }


 @override
 public boolean isvalid(string value, constraintvalidatorcontext context) {
  if (value == null || "".equals(value)) {
   return true;
  }


  enumvalidate[] enums = (enumvalidate[]) enumclass.getenumconstants();
  if(enums ==null || enums.length == 0){
   return false;
  }


  return enums[0].existvalidate(value);
 }

}

actiontypeenum:枚举类

@getter
public enum actiontypeenum implements enumvalidate<string> {


 action_invokr("invoke", "invoke"),
 unknown_error("no", "no");

 /**
  * 状态值
  */
 private string coupontype;

 /**
  * 状态描述
  */
 private string coupontypedesc;

 actiontypeenum(string coupontype, string coupontypedesc) {
  this.coupontype = coupontype;
  this.coupontypedesc = coupontypedesc;
 }


 public static string getdescbytype(string coupontype) {
  for (actiontypeenum type : actiontypeenum.values()) {
   if (type.coupontype.equals(coupontype) ) {
    return type.coupontypedesc;
   }
  }
  return null;
 }

 /**
  * 判断是否在枚举类当中
  * @param value
  * @return
  */
 @override
 public boolean existvalidate(string value) {
  if (value == null || "".equals(value)) {
   return false;
  }
  for (actiontypeenum testenum : actiontypeenum.values()) {
   if (testenum.getcoupontype().equalsignorecase(value)) {
    return true;
   }
  }
  return false;
 }

 public string getcoupontypestr() {
  return string.valueof(this.coupontype);
 }
}

globalexceptionhandler:使用springmvc提供的异常处理机制,对validationapi的异常进行封装

@restcontrolleradvice
@slf4j
public class globalexceptionhandler {

 /**
  * 忽略参数异常处理器
  *
  * @param e 忽略参数异常
  * @return response
  */
 @responsestatus(httpstatus.bad_request)
 @exceptionhandler(missingservletrequestparameterexception.class)
 public responseresult parametermissingexceptionhandler(missingservletrequestparameterexception e) {
  log.error("参数异常", e);
  return new responseresult(coupontypeenum.parameter_error.getcoupontypestr(), "请求参数 " + e.getparametername() + " 不能为空");
 }


 /**
  * 缺少请求体异常处理器
  *
  * @param e 缺少请求体异常
  * @return response
  */
 @responsestatus(httpstatus.bad_request)
 @exceptionhandler(httpmessagenotreadableexception.class)
 public responseresult parameterbodymissingexceptionhandler(httpmessagenotreadableexception e) {
  log.error("缺少请求体异常", e);
  return new responseresult(coupontypeenum.parameter_error.getcoupontypestr(), "参数体不能为空");
 }


 /**
  * 参数效验异常处理器
  *
  * @param e 参数验证异常
  * @return responseinfo
  */
 @responsestatus(httpstatus.bad_request)
 @exceptionhandler(methodargumentnotvalidexception.class)
 public responseresult parameterexceptionhandler(methodargumentnotvalidexception e) {
  log.error("参数验证异常", e);
  // 获取异常信息
  bindingresult exceptions = e.getbindingresult();
  // 判断异常中是否有错误信息,如果存在就使用异常中的消息,否则使用默认消息
  if (exceptions.haserrors()) {
   list<objecterror> errors = exceptions.getallerrors();
   if (!errors.isempty()) {
    // 这里列出了全部错误参数,按正常逻辑,只需要第一条错误即可
    fielderror fielderror = (fielderror) errors.get(0);
    return new responseresult(coupontypeenum.parameter_error.getcoupontypestr(), fielderror.getdefaultmessage());
   }
  }
  return new responseresult(coupontypeenum.parameter_error);
 }


 /**
  * 自定义参数错误异常处理器
  *
  * @param e 自定义参数
  * @return responseinfo
  */
 @responsestatus(httpstatus.bad_request)
 @exceptionhandler({businessexception.class})
 public responseresult paramexceptionhandler(businessexception e) {
  log.error("业务异常", e);
  // 判断异常中是否有错误信息,如果存在就使用异常中的消息,否则使用默认消息
  if (!stringutils.isempty(e.getmessage())) {
   return new responseresult(coupontypeenum.parameter_error.getcoupontypestr(), e.getmessage());
  }
  return new responseresult(coupontypeenum.parameter_error);
 }


 /**
  * 其他异常
  *
  * @param e
  * @return
  */
 @responsestatus(httpstatus.bad_request)
 @exceptionhandler({exception.class})
 public responseresult otherexceptionhandler(exception e) {
  log.error("其他异常", e);
  // 判断异常中是否有错误信息,如果存在就使用异常中的消息,否则使用默认消息
  if (!stringutils.isempty(e.getmessage())) {
   return new responseresult(coupontypeenum.unknown_error.getcoupontypestr(), e.getmessage());
  }
  return new responseresult(coupontypeenum.unknown_error);
 }
}

验证

请求的封装类

/**
* 指令的封装类
*/
@getter
@setter
@tostring
public class commandpojo implements serializable {
 private static final long serialversionuid = -8497328408069586664l;

 //指令
 @notnull(message = "指令为必填项,不得为空")
 @actiontypeenumvalid(message = "该指令暂不支持,暂时只支持invoke", enumclass = actiontypeenum.class)
 private string action ="invoke";

}

请求接口

@valid 用于开启请求参数校验

@restcontroller
@slf4j
@api(value = "远程调用模块")
@requestmapping("/xiyuanrpc")
public class rpccontroller {

 @postmapping("/rpcnettybyinvoke")
 @apioperation(value = "rpc远程调用")
 @invokeparametercheck
 @methodlogprint
 public responseresult rpcnettybyinvoke(@valid @requestbody commandpojo pojo) {
  return nettyclientutil.rpcnetty(pojo);
 }

}

通过knife4j访问对应接口

SpringBoot使用validation-api实现对枚举类参数校验的方法

源码

项目源码可从的我的github中获取:

到此这篇关于springboot使用validation-api实现对枚举类参数校验的方法的文章就介绍到这了,更多相关springboot枚举类参数校验内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!