首页 > 其他分享 >基于拦截器去实现数据长度等校验

基于拦截器去实现数据长度等校验

时间:2023-04-17 17:36:24浏览次数:37  
标签:拦截器 String 校验 public import 长度 cyi com annotation

因为之前基于了HandlerInterceptorAdapter去实现过我们数据的拦截。后来一想这个都可以用来对传递的数据做拦截那么这个时候我们就可以用它来加上自定义注解去实现一个入参的数据校验这样就避免了大量的逻辑。可以去实现每个入参进来的时候数据的校验等等。

package com.cyi.Interceptor;

import com.cyi.annotatio.Dex;
import com.cyi.annotatio.DexPram;
import com.cyi.util.CommonEnum;
import com.cyi.util.ResponseMeaage;
import com.cyi.util.ResponseVo;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;

/**
 * @Description: 描述
 * @Author:chenguifu
 * @Date:2023/4/14 10:31
 * @Company:公司
 * @Version:V1.0
 */
public class DexInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Method method = ((HandlerMethod) handler).getMethod();
        Class<?>[] parameterTypes = ((HandlerMethod) handler).getMethod().getParameterTypes();
        if (parameterTypes != null && parameterTypes.length > 0){
            Arrays.stream(parameterTypes).forEach(parameterType ->{
                //获取到Controller上的注解
                Dex annotation2 = parameterType.getAnnotation(Dex.class);
                if (annotation2 != null){
                    Method[] declaredMethods = parameterType.getDeclaredMethods();
                    Arrays.stream(declaredMethods).forEach(param ->{
                        Arrays.stream(parameterType.getDeclaredFields()).forEach(methodParam ->{
                            //获取属性上的注解
                            DexPram annotation = methodParam.getAnnotation(DexPram.class);
                            if (annotation != null){
                                //这个是msg
                                String message = annotation.message();
                                //这个是类型
                                Object type = annotation.type();
                                //当你要判断长度的时候需要根据数据库的存储字节去判断gbk中文占用2字节 utf-8占用3字节所以这个时候需要去进行一个更改
                                String byteType = annotation.byteType();
                                int min = annotation.min();
                                int max = annotation.max();
                                if (type.equals(String.class)){
                                    if (min > 0 || max > 0){
                                        String nameString = request.getParameter(methodParam.getName());
                                        int stringLength = getStringLength(nameString, byteType);
                                        if (stringLength == -1){
                                            ResponseVo responsetVo = ResponseMeaage.error(CommonEnum.ResponseCodeEnum.qtcw.Value, "数据长度异常", null, "");
//                                            response.getWriter().write(responsetVo.toString());
                                            throw new IndexOutOfBoundsException("数据长度异常");
                                        }
                                        if (min > 0){
                                            if (stringLength >= min){
                                                ResponseVo responsetVo = ResponseMeaage.error(CommonEnum.ResponseCodeEnum.qtcw.Value, message, null, "");
                                                throw new IndexOutOfBoundsException(message);
                                            }
                                        }

                                    }

                                }
                            }
                        });
                    });
                }
            });
        }
        return  true;
    }

    public static int getStringLength(Object str,String encoding) {
        if (str == null){
            return 0;
        }
        try {
            return str.toString().getBytes(encoding).length;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return -1;
    }
}
package com.cyi.config;

import com.cyi.Interceptor.DexInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @Description: 描述
 * @Author:chenguifu
 * @Date:2023/4/14 10:35
 * @Company:公司
 * @Version:V1.0
 */
@Configuration
public class MyConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new DexInterceptor()).addPathPatterns("/**");
    }



}
package com.cyi.annotatio;

import java.lang.annotation.*;
import java.util.Date;


/**
 * @Description: 描述
 * @Author:chenguifu
 * @Date:2023/4/14 10:22
 * @Company:公司
 * @Version:V1.0
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@Documented
public @interface Dex {

}
package com.cyi.annotatio;

import java.lang.annotation.*;

/**
 * @Description: 描述
 * @Author:chenguifu
 * @Date:2023/4/14 11:18
 * @Company:公司
 * @Version:V1.0
 */

@Documented
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface DexPram {
    int max() default 0;
    int min() default 0;
    String message() default "";
    String byteType() default "utf-8";
    Class type() default String.class;
    Class<?> fallback() default void.class;
}
package com.cyi.bean;

import com.cyi.annotatio.Dex;
import com.cyi.annotatio.DexPram;

/**
 * @Description: 描述
 * @Author:chenguifu
 * @Date:2023/4/14 10:23
 * @Company:公司
 * @Version:V1.0
 */
@Dex
public class TestBean {
    @DexPram(message = "最大不能超过10")
    private String name;
    private String ll;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLl() {
        return ll;
    }

    public void setLl(String ll) {
        this.ll = ll;
    }
}

 

标签:拦截器,String,校验,public,import,长度,cyi,com,annotation
From: https://www.cnblogs.com/xiaoguifu/p/17326514.html

相关文章

  • Java 4种校验注解(值校验、范围校验、长度校验、格式校验)
    1Maven依赖<!--第一种方式导入校验依赖--><dependency><groupId>javax.validation</groupId><artifactId>validation-api</artifactId><version>2.0.1.Final</version></dependency><!--第二种方式导入校验......
  • elementui表单循环添加校验
    1<el-form2:model="dynamicValidateForm"3ref="dynamicValidateForm"4:inline="true"5>6<templatev-for="(item,index)indynamicValidateForm.domains">......
  • 解决密码校验问题
    密码教研中的问题http协议是无状态的协议,每次请求间不能实现数据共享.这样的状况下,不能在后续请求中获取是否登录的数据解决方法1.在员工登录成功后,需要将用户登录成功的信息存起来,记录用户已经登录成功的标记。2.在浏览器发起请求时,需要在服务端进行统一拦截,拦截后进行登......
  • SpringMVC-JSR303和拦截器
    1.JSR3031.1.什么是JSR303JSR是JavaSpecificationRequests的缩写,意思是Java规范提案。是指向JCP(JavaCommunityProcess)提出新增一个标准化技术规范的正式请求。任何人都可以提交JSR,以向Java平台增添新的API和服务。JSR已成为Java界的一个重要标准。JSR-303是JAVAEE6......
  • 洛谷T226686 长度为2的子串
    题目描述给你一个长度为n 的由大写的英文字母组成的字符串,请你找出出现频率最高的长度为2的子串。输入格式包括两行。第一行是一个正整数n,表示字符串长度。第二行是长度为n的大写英文字母组成的字符串。(2<=n<=100)输出格式包括一行。一个长度为2的字符串,该字符串为输入......
  • 2023.04.16 - TS编译之后的JS不具备校验功能
    TypeScript编译后的JavaScript文件并不具备类型检查的功能,因为JavaScript语言本身是动态类型、弱类型的,在运行时无法推断变量的类型,只能在编译时推断。而将TypeScript文件编译成JavaScript文件时,会把TypeScript中的类型声明和类型检查都去掉,只保留JavaScript代码,所以......
  • Android开发,使用的是OkHttp和Reftrofit,用的是Kotlin协程,用Kotlin写一个网络拦截器,模拟
    首先,我们需要定义一个网络拦截器类,继承自OkHttp的Interceptor接口:classLoginInterceptor:Interceptor{overridefunintercept(chain:Interceptor.Chain):Response{//模拟登录请求,这里可以根据具体情况进行修改valrequest=chain.request().ne......
  • HashMap内部的bucket(桶)数组长度为什么一直都是2的整数次幂?
    这样做有两个好处:第一,可以通过(table.length-1)&key.hash()这样的位运算快速寻址,第二,在HashMap扩容的时候可以保证同一个桶中的元素均匀的散列到新的桶中,具体一点就是同一个桶中的元素在扩容后一半留在原先的桶中,一半放到了新的桶中。......
  • mvc多拦截器配置
        ......
  • mvc拦截器配置与方法参数
          ......