当前位置:   article > 正文

重复提交校验+HttpServletRequest 流数据不可重复读_java 接口防止重复提交,校验请求体

java 接口防止重复提交,校验请求体

功能背景

第三方想要获取我们的接口数据,我们对请求进行统一鉴权校验、还有对于重复提交进行拦截,这些都要获取当前请求的参数,在进行校验,防止重复提交。

实现

①编写自定义注解

import java.lang.annotation.*;

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface RedisLock {
    int expire() default 5;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

然后在我们需要验证重复提交的方法上加上@RedisLock注解
在这里插入图片描述
②编写自定义拦截器,书写业务逻辑

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
public class RepeatSubmitInterceptor extends HandlerInterceptorAdapter {

    private static final Logger LOGGER = LoggerFactory.getLogger(RepeatSubmitInterceptor.class);

    @Value("${spring.profiles.active}")
    private String springProfilesActive;
    @Value("${spring.application.name}")
    private String springApplicationName;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            RedisLock redisLock = method.getAnnotation(RedisLock.class);
            if (redisLock != null) {
                //设置缓存时间
                Integer expire = redisLock.expire();
                if (expire < 0) {
                    expire = 5;
                }
                LOGGER.info("进入重复提交效验");
                //就行重复效验
                if (isRepeatSubmit(request, expire)) {
                    ServletUtils.writeResponse(response, ResultEnum.CODE_6__REPETITION_OPERATION);
                    return false;
                }
            }
        }
        return true;
    }

    private Boolean isRepeatSubmit(HttpServletRequest request, Integer expire) throws IOException {
//        String currParams = getBodyString(request);
//        if (StringUtils.isBlank(currParams)) {
//            currParams = JSON.toJSONString(request.getParameterMap());
//        }
//        //参数加密
//        String md5Params = MD5Utils.getMD5(currParams);
        //设置Key值
        //同一个人,5秒内不能重复保存同一个接口
        LoginUserBo userBo = UserUtils.getUserFromSession();
        String key = "repeatSubmitLock:" + springApplicationName + ":" + springProfilesActive + ":" + userBo.getOrgNum() + ":" + userBo.getName() + ":" + request.getRequestURI();
        LOGGER.info(key);
        //加入分布式事务锁
        boolean exist = JedisUtils.tryGetDistributedLock(key, request.getRequestURI(), expire);
        if (!exist) {
            return true;
        }
        return false;
    }

    public static String getBodyString(ServletRequest request) {
        //暂时不加参数效验,未解决request流只读一次
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = null;
        try (InputStream inputStream = request.getInputStream()) {
            reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
            String line = "";
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            LOGGER.warn("getBodyString出现问题!");
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    LOGGER.error(ExceptionUtils.getMessage(e));
                }
            }
        }
        return sb.toString();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93

以上代码仅实现了同一个人,5秒内不能重复保存同一个接口,对于getBodyString中的request流只读一次问题未解决。

HttpServletRequest 流数据不可重复读

成熟且常见的解决方案就是通过拦截器对任何请求,进行拦截,只要在拦截器中获取当前请求的参数即可。奈何在拦截器中只有拿到request使用 request.getParameter() 等方法时,只能拿到表单数据和地址栏参数,并不能拿到请求头数据。当使用request.getInputStream(),能拿到参数。但是在具体接口业务流程中,再使用request.getParameter() 等方法,传入参数就获取不到了。
在这里插入图片描述
我们会发现在拦截器中使用request.getInputStream()方法拿到参数后,再走我们实际的调用接口是会拿不到参数,说流已关闭,因为流只能被读一次。

解决方案

重写HttpServletRequestWrapper包装类,使用过滤器在任何请求之前将线程中的HttpServletRequest替换成包装好的,在调用getInputStream方法时,将流数据同时写到缓存。后面想获取参数,直接读取缓存数据即可。这样就可以实现Request的内容多次读取。
①封装 request 自定义类 ContentCachingRequestWrapper

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 *
 * 重写 HttpServletRequestWrapper
 *
 * @Author: didi
 * @Date 2022-09-21
 */
public class ContentCachingRequestWrapper extends HttpServletRequestWrapper {
    private final byte[] body;

    public ContentCachingRequestWrapper(HttpServletRequest request) {
        super(request);
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8))){
            String line = "";
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        body = sb.toString().getBytes(StandardCharsets.UTF_8);
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {

        final ByteArrayInputStream inputStream = new ByteArrayInputStream(body);

        return new ServletInputStream() {

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read() throws IOException {
                return inputStream.read();
            }
        };
    }

    public byte[] getBody() {
        return body;
    }
    /**
     * 获取请求Body
     *
     * @return String
     */
    public String getBodyString() {
        return new String(body);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78

②自定义过滤器

import com.github.pagehelper.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import javax.servlet.*;
import javax.servlet.FilterConfig;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @Author didi
 * @Create 2022/9/21 9:04
 */
public class ReplaceStreamFilter  implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(ReplaceStreamFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("StreamFilter初始化...");
    }


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String contentType = request.getContentType();
        if(!StringUtil.isEmpty(contentType) && contentType.contains("multipart/form-data")) {
            chain.doFilter(request, response);
            return;
        }
        if(request instanceof HttpServletRequest) {
             request = new ContentCachingRequestWrapper((HttpServletRequest) request);
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        logger.info("StreamFilter销毁...");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

③添加过滤器配置

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;

/**
 * @Author didi
 * @Description 过滤器配置类
 * @Create 2022/9/21 9:06
 */
@Configuration
public class FilterContextConfig {
    /**
     * 注册过滤器
     *
     * @return FilterRegistrationBean
     */
    @Bean
    public FilterRegistrationBean someFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(replaceStreamFilter());
        registration.addUrlPatterns("/*");
        registration.setName("streamFilter");
        return registration;
    }

    /**
     * 实例化StreamFilter
     *
     * @return Filter
     */
    @Bean(name = "replaceStreamFilter")
    public Filter replaceStreamFilter() {
        return new ReplaceStreamFilter();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37

封装后的request流具体实现方法

ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request);
String currParams = requestWrapper.getBodyString();
  • 1
  • 2

完整的自定义拦截器

public class RepeatSubmitInterceptor extends HandlerInterceptorAdapter {

    private static final Logger LOGGER = LoggerFactory.getLogger(RepeatSubmitInterceptor.class);

    @Value("${spring.profiles.active}")
    private String springProfilesActive;
    @Value("${spring.application.name}")
    private String springApplicationName;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            RedisLock redisLock = method.getAnnotation(RedisLock.class);
            if (redisLock != null) {
                //设置缓存时间
                Integer expire = redisLock.expire();
                if (expire < 0) {
                    expire = 5;
                }
                LOGGER.info("进入重复提交效验");
                //就行重复效验
                if (isRepeatSubmit(request, expire)) {
                    ServletUtils.writeResponse(response, ResultEnum.CODE_6__REPETITION_OPERATION);
                    return false;
                }
            }
        }
        return true;
    }

    /**
     *5秒内判断重复提交 同一个人同一个参数同一个参数(地址栏+请求体,不包含文件流请求体)为重复提交进行拦截
     * @param request 当前请求
     * @param expire redis
     * @return
     */
    private Boolean isRepeatSubmit(HttpServletRequest request, Integer expire)  {
        /**
         *  TODO ContentCachingRequestWrapper被new两次,重复新建,按理来说整个request以及被替换,无需在new
         *  在没有其他框架封装request时可以进行强转(比如zuul,shiro,security)
         */
        String currParams="";
        String contentType = request.getContentType();
        Map<String, String[]> parameterMap = request.getParameterMap();
        if (!parameterMap.isEmpty()) {
            currParams = JSON.toJSONString(parameterMap);
        }
        // 如果上传文件不能对request进行包装,提升流已经关闭
        if(StringUtil.isNotEmpty(contentType) && !contentType.contains("multipart/form-data")) {
            ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request);
            String bodyString = requestWrapper.getBodyString();
            currParams = StringUtils.isEmpty(currParams) ? bodyString : currParams + bodyString;
        }
        LOGGER.info("requestParamJson --> {}", currParams);
        //参数加密
        String md5Params = MD5Utils.getMD5(currParams);
        //设置Key值
        //同一个人,5秒内不能重复保存同一个接口
        LoginUserBo userBo = UserUtils.getUserFromSession();
        String key = "repeatSubmitLock:" + springApplicationName + ":" + springProfilesActive + ":" + userBo.getOrgNum() + ":" + userBo.getName() + ":" + request.getRequestURI()+":"+md5Params;
        LOGGER.info(key);
        //加入分布式事务锁
        boolean exist = JedisUtils.tryGetDistributedLock(key, request.getRequestURI(), expire);
        if (!exist) {
            return true;
        }
        return false;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/550838
推荐阅读
相关标签
  

闽ICP备14008679号