首页 > 编程语言 >springboot-javax.validation编写自定义校验注解

springboot-javax.validation编写自定义校验注解

时间:2024-07-01 16:22:39浏览次数:1  
标签:return springboot 自定义 int minLength import validation public String

引入依赖:

<!--jsr 303-->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>

<!-- hibernate validator-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.0.Final</version>
</dependency>
View Code

自定义校验注释:

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Constraint(validatedBy = CheckLengthFetureValidator.class)
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface CheckLengthFeture {

    int minLength() default 0;

    int maxLength() default 0;

    int strictLength() default 0;

    boolean required() default false;

    String message() default "";

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

    Class<? extends Payload>[] payload() default {};
}
View Code
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class CheckLengthFetureValidator implements ConstraintValidator<CheckLengthFeture, String> {

    private int minLength;

    private int maxLength;

    private int strictLength;

    private boolean required;

    @Override
    public void initialize(CheckLengthFeture feture) {
        this.minLength = feture.minLength();
        this.maxLength = feture.maxLength();
        this.strictLength = feture.strictLength();
        this.required = feture.required();
    }

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        if (StringUtils.isNotBlank(s)) {
            if ((minLength != 0 || maxLength != 0) && strictLength != 0) {
                return false;
            } else {
                if (minLength != 0 && maxLength == 0) {
                    return CommonUtil.strlen(s) >= minLength ? true : false;
                } else if (minLength == 0 && maxLength != 0) {
                    return CommonUtil.strlen(s) <= maxLength ? true : false;
                } else if (minLength != 0 && maxLength != 0) {
                    return CommonUtil.strlen(s) >= minLength && CommonUtil.strlen(s) <= maxLength ? true : false;
                } else if (strictLength != 0) {
                    return CommonUtil.strlen(s) == strictLength ? true : false;
                } else {
                    return false;
                }
            }
        } else {
            if (required) {
                return false;
            } else {
                return true;
            }
        }
    }
}
View Code
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

@Slf4j
public class CommonUtil {
    private static final Logger logger = LoggerFactory.getLogger(CommonUtil.class);
    private static Random random = new Random();

    public static String getUUID() {
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        return uuid;
    }

    /**
     * 将String的List泛型转换成以;号分隔的字符串
     *
     * @param stringList
     * @return
     */
    public static String transListToStr(List<String> stringList) {
        if (stringList != null && stringList.size() > 0) {
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append("");
            Iterator<String> stringIterator = stringList.iterator();
            while (stringIterator.hasNext()) {
                stringBuffer.append(stringIterator.next());
                if (stringIterator.hasNext()) {
                    stringBuffer.append(";");
                }
            }
            return stringBuffer.toString();
        } else {
            return null;
        }
    }

    /**
     * 将字符串以split分隔,并且添加到List中
     *
     * @param str
     * @param split
     * @return
     */
    public static List<String> transStrToList(String str, String split) {
        if (StringUtils.isNotBlank(str)) {
            String[] strings = str.split(split);
            List<String> stringList = new ArrayList<>();
            for (String string : strings) {
                stringList.add(string);
            }
            return stringList;
        } else {
            return null;
        }
    }

    /**
     * 判断字符串长度,当为汉字时,以2个字节计算
     *
     * @param str
     * @return
     */
    public static int strlen(String str) {
        int len = 0;
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
                len++;
            } else {
                len += 2;
            }
        }
        return len;
    }

}
View Code
@CheckLengthFeture(maxLength = 6, required = true, message = "")
    private String xxx;
    @CheckLengthFeture(required = true, message = "")
    private String xxx;
View Code

 

 

声明:此博客为个人学习之用,如与其他作品雷同,纯属巧合,转载请指明出处!  

标签:return,springboot,自定义,int,minLength,import,validation,public,String
From: https://www.cnblogs.com/zhihuifan10/p/18278291

相关文章

  • ros micro-ros 自定义消息接口
    本节课最终效果是:通过自定义的服务接口控制开发板上的OLED显示器的内容。ros2servicecall/oled_controlfishbot_interfaces/srv/OledControl"{px:0,py:0,data:'oledcontrolbyservice~'}" 一、新建工程添加依赖新建example14_custom_interface,注意请不要将工......
  • springboot+vue前后端分离项目-vue项目搭建6-文件上传下载
    1.新增com/example/demo/controller/FileController.javapackagecom.example.demo.controller;importcn.hutool.core.io.FileUtil;importcn.hutool.core.util.IdUtil;importcn.hutool.core.util.StrUtil;importcom.example.demo.common.Result;importjakarta.ser......
  • QT 使用Q_PLUGIN_METADATA实现自定义插件
    1.创建一个继承自QObject的类,并在类的实现文件中使用Q_PLUGIN_METADATA宏定义插件的元数据信息。这个宏通常包含插件的元数据,如插件的标识符、版本号等。2.在插件项目的.pro文件中添加QT += core gui widgets以确保能够使用Qt的相关功能。3.在主应用程序中使用QPluginLoade......
  • springboot+vue+mybatis农业信息管理_种植员+PPT+论文+讲解+售后
    网络的广泛应用给生活带来了十分的便利。所以把农业信息管理与现在网络相结合,利用java技术建设农业信息管理系统,实现农业信息管理的信息化。则对于进一步提高农业信息管理发展,丰富农业信息管理经验能起到不少的促进作用。农业信息管理系统能够通过互联网得到广泛的、全面的宣......
  • springboot+vue+mybatis奶茶管理系统+PPT+论文+讲解+售后
    由于科学技术的快速发展,人们的生活也与信息时代的发展相关。同时,随着市场化和经济化的发展,国内很多行业已经意识到了这一点,为了提升行业的竞争力,就应当率先把握机会。于是在互联网的默化潜移影响下,餐饮业相关网站就是在这种情况下产生和发展起来的。奶茶在线订购系统是一个面......
  • 最新AIGC系统源码-ChatGPT商业版系统源码,自定义ChatGPT指令Promp提示词,AI绘画系统,AI换
    目录一、前言系统文档二、系统演示核心AI能力系统快速体验三、系统功能模块3.1AI全模型支持/插件系统AI模型提问文档分析​识图理解能力3.2GPts应用3.2.1GPTs应用3.2.2GPTs工作台3.2.3自定义创建Promp指令预设应用3.3AI专业绘画3.3.1文生图/图生图(垫图)......
  • springBoot集成Spring Cloud Alibaba Sentinel
    一、背景介绍:Sentinel·alibaba/spring-cloud-alibabaWiki·GitHub二、Sentinel介绍随着微服务的流行,服务和服务之间的稳定性变得越来越重要。 Sentinel 以流量为切入点,从流量控制、熔断降级、系统负载保护等多个维度保护服务的稳定性。Sentinel 具有以下特征:......
  • Dubbo 如何自定义协议为业务通信带来扩展
    Solomon_肖哥弹架构跟大家“弹弹”Dubbo自定义协议扩展欢迎点赞,收藏,关注。关注本人的公众号Solomon肖哥弹架构获取更多精彩内容Dubbo自定义协议扩展1、扩展说明RPC协议扩展,封装远程调用细节。契约:当用户调用refer()所返回的Invoker对象的invoke()方法......
  • 1974Springboot医院远程诊断管理系统idea开发mysql数据库web结构java编程计算机网页源
    一、源码特点 springboot医院远程诊断管理系统是一套完善的信息系统,结合springboot框架和bootstrap完成本系统,对理解JSPjava编程开发语言有帮助系统采用springboot框架(MVC模式开发),系统具有完整的源代码和数据库,系统主要采用B/S模式开发。springboot医院远程诊断系统......
  • 基于Springboot的电子招投标系统。Javaee项目,springboot项目。
    演示视频:基于Springboot的电子招投标系统。Javaee项目,springboot项目。项目介绍:采用M(model)V(view)C(controller)三层体系结构,通过Spring+SpringBoot+Mybatis+Vue+Maven+Layui+Elementui来实现。MySQL数据库作为系统数据储存平台,实现了基于B/S结构的Web系统。界面简......