关于防重复提交踩的一次坑

首先,先说一下防重复的做法:

1、思路:

        首先前端做处理,但是很显然是治标不治本的,所以后端肯定也是要把好关的,确定重复提交的定义:在短时间内,同一个IP,请求同一个方法,提交的参数都相同,则认为是重复提交。

那我们只要做到在每次接收到请求时,先校验前面是不是已经收到过相同的请求,如果有则直接返回请求频繁,如果没有则放行,继续业务代码。

2、解决代码:

         配置拦截器,springboot和spring mvc如何配置可自定百度(如springboot如何配置拦截器),以下是拦截器的代码

import java.util.Objects;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

public class WebHandlerInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if(handler instanceof HandlerMethod) {
			try {
				//这里是防重复提交,使用时只需要在对应的controller方法上加上RepeatCheck注解,默认是5秒内只允许一次相同参数的提交。
				HandlerMethod handlerMethod = (HandlerMethod) handler;
				RepeatCheck annotation = handlerMethod.getMethodAnnotation(RepeatCheck.class);
				if (Objects.isNull(annotation)) {
					return true;
				}
				RequestUtil requestUtil = new RequestUtil(request);
				boolean includeIp = annotation.includeIp();
				String md5 = requestUtil.getParametersMd5(includeIp, annotation.excludeKeys());
                //CacheUtils代码再后面,是自己实现的一个内存缓存,当然也可以换成其他的,比如redis等
				CacheData<?> data = CacheUtils.getData(md5);
				if(data != null) {
                    //这里自己定义请求频繁异常的返回值
					response.setHeader("Content-Type", "application/json");
					Result<?> failure = Result.Failure("3333", "请求频繁");
					failure.setExt(data.getTtl());//剩余锁定时间
					failure.setSysMessage(data.getHits()+"");//重复请求次数
					response.getWriter().print(JSONObject.toJSONString(failure));
					return false;
				}
				CacheUtils.set(md5, md5, annotation.time(), annotation.timeUnit());
			} catch (Exception e) {
				// ignore
			}
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		HeaderThreadLocal.clear();
	}

}

 RequestUtil.java   对request的操作工具类,可以取出get和post请求的参数



import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;

/**
* @author Mr Gu
* @version V1.1
* <p>time: 2022年6月17日 上午9:30:45</p> 
* <p>Description:</p>
*/
public class RequestUtil {
	
	private HttpServletRequest request;

    public RequestUtil(HttpServletRequest request) {
        this.request = request;
    }

    public String getParameters(String... excludeKeys) {
    	
    	List<String> asList = Arrays.asList(excludeKeys);
    	
    	String method = request.getMethod();
    	String data = "";
    	if("POST".equals(method.toUpperCase()) && request.getContentType().contains("application/json")) {
    		data = getPostData(asList);
    	} else {
    		data = getGetData(asList);
		}
        return data;
    }
    
    private String getGetData(List<String> asList) {
    	StringBuilder sb = new StringBuilder();
		Enumeration<String> paraNames = request.getParameterNames();
		if (paraNames == null) {
			return null;
		}
		while (paraNames.hasMoreElements()) {
			String paraName = paraNames.nextElement();
			if(!asList.contains(paraName)) {
				sb.append("&").append(paraName).append("=").append(request.getParameter(paraName));
			}
		}
		return sb.toString();
    }
    
    private String getPostData(List<String> asList) {
    	String body = new NewHttpRequestWrapper(request).getBody();
    	JSONObject parseObject = JSONObject.parseObject(body);
    	for (String string : asList) {
    		parseObject.remove(string);
		}
    	return parseObject.toString();
    }
    
    public String getParametersMd5(boolean ip, String... excludeKeys) {
    	String str = request.getRequestURI()+getParameters(excludeKeys);
    	if(ip) {
    		str+=getIp();
    	}
		return encrypt2ToMD5(str);
    }
    
    public String getHeader(String headerName) {
        return request.getHeader(headerName);
    }

    public String getReferer() {
        return getHeader("Referer");
    }

    public String getUa() {
        return getHeader("User-Agent");
    }

    public String getIp() {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public String getRequestUrl() {
        return request.getRequestURL().toString();
    }

    public String getServletPath() {
        return request.getServletPath();
    }

    public String getMethod() {
        return request.getMethod();
    }
	
    static char[] hex = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; 
	
	public static String encrypt2ToMD5(String str) {
		// 加密后的16进制字符串
		String hexStr = "";
		try {
			// 此 MessageDigest 类为应用程序提供信息摘要算法的功能
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			// 转换为MD5码
			byte[] digest = md5.digest(str.getBytes("utf-8"));
			int len = digest.length;   
		    StringBuffer result = new StringBuffer();    
		    for (int i = 0; i < len; i++) {   
		        byte byte0 = digest[i];   
		        result.append(hex[byte0 >>> 4 & 0xf]);   
		        result.append(hex[byte0 & 0xf]);   
		    }
		    hexStr = result.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return hexStr;
	}
    
}

CacheUtils.java 内存缓存工具类



import java.util.Calendar;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * 
* <p>Description: 基于Map的缓存</p>  
* @author Mr Gu
* @version V1.1
* <p>time: 2022年6月17日 上午9:43:54</p>
 */
@SuppressWarnings("rawtypes")
public class CacheUtils {
	
	public static Map<String, CacheData> cache = new ConcurrentHashMap<String, CacheUtils.CacheData>();
	
	/**
	 *	 启动定时任务清理过期缓存,避免内存溢出
	 */
	static {
		Timer t = new Timer("cache-clear-timer");
		t.schedule(new ClearTimerTask(cache), 0, 60000);
	}

	/**
	 * 获取缓存数
	 * 
	 * @return CacheSize
	 */
	public static int getCacheSize() {
		return cache.size();
	}

	/**
	 * 
	 * <p>Description: 设置缓存,默认12小时过期</p>  
	 * @author Mr Gu
	 * @version 2021年3月24日 下午4:59:10 
	 * @param <T> T
	 * @param key 建
	 * @param t 值
	 */
	public static <T> void set(String key, T t) {
		cache.put(key, new CacheData<>(t, 43200000));
	}

	/**
	 * 设置缓存,指定过期时间expire(单位毫秒)
	 * 
	 * @param key 建
	 * @param t	值
	 * @param <T> T
	 * @param expire 过期时间
	 */
	public static <T> void set(String key, T t, long expire) {
		cache.put(key, new CacheData<>(t, expire));
	}
	
	/**
	 * 
	 * @param <T> T
	 * @param key 建
	 * @param t 值
	 * @param expire 过期时间
	 * @param timeUnit 时间单位
	 */
	public static <T> void set(String key, T t, long expire, TimeUnit timeUnit) {
		cache.put(key, new CacheData<>(t, timeUnit.toMillis(expire)));
	}
	
	/**
	 * 根据key获取指定缓存
	 * @param <T> T
	 * @param key 建
	 * @return 值
	 */
	@SuppressWarnings("unchecked")
	public static <T> T get(String key) {
		CacheData<T> data = cache.get(key);
		if (null == data) {
			return null;
		}
		if (data.isExpire()) {
			remove(key);
			return null;
		}
		data.addHits();
		return data.getData();
	}
	
	@SuppressWarnings("unchecked")
	public static <T> CacheData getData(String key) {
		CacheData<T> data = cache.get(key);
		if (null == data) {
			return null;
		}
		if (data.isExpire()) {
			remove(key);
			return null;
		}
		data.addHits();
		return data;
	}
	
	@SuppressWarnings("unchecked")
	public synchronized static <T> T getSynchronization(String key) {
		CacheData<T> data = cache.get(key);
		if (null == data) {
			return null;
		}
		if (data.isExpire()) {
			remove(key);
			return null;
		}
		data.addHits();
		return data.getData();
	}

	@SuppressWarnings("unchecked")
	public static <T> int getHits(String key) {
		CacheData<T> data = cache.get(key);
		if (null == data) {
			return 0;
		}
		if (data.isExpire()) {
			remove(key);
			return 0;
		}
		return data.getHits();
	}

	@SuppressWarnings("unchecked")
	public static <T> long getTtl(String key) {
		CacheData<T> data = cache.get(key);
		if (null == data) {
			return 0;
		}
		if (data.isExpire()) {
			remove(key);
			return 0;
		}
		return data.getTtl();
	}

	public static <T> Map<String, CacheData> get() {
		return cache;
	}

	/**
	 * 查询是否包含某key
	 * 
	 * @param key 建
	 * @return	是否存在
	 */
	public static Boolean hasKey(String key) {
		CacheData data = cache.get(key);
		if (null == data) {
			return false;
		}
		if (data.isExpire()) {
			remove(key);
			return false;
		}
		return true;
	}

	/**
	 * 移除指定key缓存
	 * 
	 * @param key 建
	 */
	public static void remove(String key) {
		cache.remove(key);
	}

	/**
	 * 移除所有缓存
	 */
	public static void removeAll() {
		cache.clear();
	}
	
	/**
	 * 
	 * <p>Description: 模糊删除</p>  
	 * @author Mr Gu
	 * @version 2021年3月25日 上午10:03:33 
	 * @param keyLike keyLike
	 * @param exa exa
	 */
	public static void removeAllByKeyLike(String keyLike,String exa) {
		Set<String> keys = cache.keySet();
		Iterator<String> iterator = keys.iterator();
		while (iterator.hasNext()) {
			String key = iterator.next();
			if(key.contains(keyLike)) {
				remove(key);
				iterator.remove();
			}
		}
	}
	
	public static class CacheData<T> {
		// 缓存数据
		private T data;
		// 过期时间(单位,毫秒)
		private long expireTime;

		private int hits;

		public CacheData(T t, long expire) {
			this.data = t;
			if (expire <= 0) {
				this.expireTime = 0L;
			} else {
				this.expireTime = Calendar.getInstance().getTimeInMillis() + expire;
			}
		}

		/**
		 * 判断缓存数据是否过期
		 * 
		 * @return true表示过期,false表示未过期
		 */
		public boolean isExpire() {
			if (expireTime <= 0) {
				return false;
			}
			if (expireTime > Calendar.getInstance().getTimeInMillis()) {
				return false;
			}
			return true;
		}

		public long getTtl() {
			return expireTime - Calendar.getInstance().getTimeInMillis();
		}

		public T getData() {
			return data;
		}

		public int getHits() {
			return hits;
		}

		public void addHits() {
			this.hits = this.hits + 1;
		}

	}

	/**
	 * 清理过期数据定时任务
	 */
	private static class ClearTimerTask extends TimerTask {

		Map<String, CacheData> cache;

		public ClearTimerTask(Map<String, CacheData> cache) {
			this.cache = cache;
		}

		@Override
		public void run() {
			Set<String> keys = cache.keySet();
			for (String key : keys) {
				CacheData<?> data = cache.get(key);
				if (data.expireTime <= 0) {
					continue;
				}
				if (data.expireTime > Calendar.getInstance().getTimeInMillis()) {
					continue;
				}
				remove(key);
			}
			
		}
	}
	
}

注解:RepeatCheck.java 在需要的controller接口上添加该注解

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.concurrent.TimeUnit;

@Retention(RUNTIME)
@Target(METHOD)
/**
* @author Mr Gu
* @version V1.1
* <p>time: 2022年6月17日 上午9:19:28</p> 
* <p>Description:</p>
*/
public @interface RepeatCheck {
	
	/**
	 * 
	 * <p>Description: 是否加入IP</p>  
	 * @author Mr Gu
	 * @version V1.1
	 * <p>time: 2022年6月17日 上午10:15:49</p> 
	 * @return
	 */
	boolean includeIp() default true;
	
	/**
	 * 
	 * <p>Description: 需要排除的属性</p>
	 * @author Mr Gu
	 * @version V1.1
	 * <p>time: 2022年6月17日 上午9:22:18</p> 
	 * @return
	 */
	String[] excludeKeys() default "";
	
	/**
	 * 
	 * <p>Description: 时间内只允许一次请求,默认5秒内,相同参数的请求只允许通过一次。</p>  
	 * @author Mr Gu
	 * @version V1.1
	 * <p>time: 2022年6月17日 上午9:26:11</p> 
	 * @return
	 */
	int time() default 5;
	
	/**
	 * 
	 * <p>Description: 时间单位</p>  
	 * @author Mr Gu
	 * @version V1.1
	 * <p>time: 2022年6月17日 上午9:27:14</p> 
	 * @return
	 */
	TimeUnit timeUnit() default TimeUnit.SECONDS;
	
}

接下来是最重要的一个:过滤器,因为我们在拦截器里面读取了POST提交的参数以后,这个流就已经被读过一次了,那这个流是不能再被读取的,会导致业务代码里面读取参数的时候会报错,所以这里用一个包装器把流包装一下,获取完参数,在把流塞回去。但是这里注意了,不要处理文件上传的流,否则会有问题,当然你也可以对上传流做特殊处理,我这里就直接判断是上传流的话就不处理了。这个需要配置的,不知道的可以自行百度(如springboot如何配置过滤器)


import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
* @author Mr Gu
* @version 1.0.0
* @date: 2022年6月21日 下午3:15:03
* <p>Description:</p>
*/
public class RequestFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
		ServletRequest requestWrapper = null;
        if(servletRequest instanceof HttpServletRequest) {
        	HttpServletRequest request = (HttpServletRequest) servletRequest;
        	String contentType = request.getContentType();
        	String method = "multipart/form-data";
        	if(contentType != null && !contentType.contains(method)) {//如果是上传类型,就不处理了,这里非常关键,当然这里也有很多其他写法。
        		requestWrapper = new NewHttpRequestWrapper((HttpServletRequest) servletRequest);
        	}
        }
        if(requestWrapper == null) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            filterChain.doFilter(requestWrapper, servletResponse);
        }
	}

	@Override
	public void destroy() {
		
	}

}

这个是流包装器,就是读完流,再把流塞回去



import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
* @author Mr Gu
* @version 1.0.0
* @date: 2022年6月21日 下午3:09:45
* <p>Description:</p>
*/
public class NewHttpRequestWrapper extends HttpServletRequestWrapper {
	
	private final String body;
	
	public NewHttpRequestWrapper(HttpServletRequest request) {
		super(request);
		StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;
        InputStream inputStream = null;
        try {
            inputStream = request.getInputStream();
            if (inputStream != null) {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                char[] charBuffer = new char[128];
                int bytesRead = -1;
                while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                    stringBuilder.append(charBuffer, 0, bytesRead);
                }
            } else {
                stringBuilder.append("");
            }
        } catch (IOException ex) {

        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        body = stringBuilder.toString();
	}

	@Override
	public ServletInputStream getInputStream() throws IOException {
		final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());
		return new ServletInputStream() {
			
			@Override
			public int read() throws IOException {
				return byteArrayInputStream.read();
			}
		};
	}
	
	@Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }
	
	public String getBody() {
	    return body;
	}

}

到这里,基本上就完事了,在controller上加上这个注解,就可以去试一下了。

@RequestMapping(value = "/test", method = RequestMethod.POST)
    @RepeatCheck(excludeKeys = {"customerId"}, includeIp = false)
    public Result<?> test2(@RequestBody OrgOtherNameDO requestData) {
    	return Result.Success("成功");
    }

如果遇到问题的话,就给我留言。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值