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

因为之前基于了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;
    }
}

 

posted @ 2023-04-17 17:16  小福gui  阅读(62)  评论(0)    收藏  举报