importorg.apache.commons.lang3.StringUtils;importorg.springframework.stereotype.Component;importorg.springframework.web.method.HandlerMethod;importorg.springframework.web.servlet.handler.HandlerInterceptorAdapter;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjava.lang.reflect.Method;importjava.util.Arrays;importjava.util.Map;importjava.util.Set;/*** 重复请求阻止拦截器*/@Component("resubmitInterceptorHandler")public class ResubmitInterceptorHandler extendsHandlerInterceptorAdapter {private RedisUtils redisUtils;//自定义
publicResubmitInterceptorHandler(RedisUtils redisUtils) {this.redisUtils =redisUtils;
}/*** 拦截重复提交的请求
*
*@paramrequest
*@paramresponse
*@paramhandler
*@return*@throwsException*/@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throwsException {
HandlerMethod method=(HandlerMethod) handler;
Resubmit resubmit= method.getMethodAnnotation(Resubmit.class);if (resubmit == null) {return true;
}else{
Long seconds=resubmit.seconds();//获取重复提交的键值
String key =getKey(request, method);
String value= redisUtils.get(key, String.class);if(StringUtils.isBlank(value)) {//如果存在就存储到redis中
redisUtils.set(key, seconds.toString(), seconds);return true;
}else{throw new Exception("请不要在" + seconds + "秒内重复请求");
}
}
}/*** 获取redis存储的键
*
*@paramrequest
*@parammethod
*@return
*/
privateString getKey(HttpServletRequest request, HandlerMethod method) {
StringBuffer sb= newStringBuffer();
String requestURI=request.getRequestURI();//拼接请求路径
sb.append(requestURI);
Method targetMethod=method.getMethod();//拼接目标方法名称
sb.append(targetMethod.getName());
Map parameterMap =request.getParameterMap();if (parameterMap != null) {
Set> entries =parameterMap.entrySet();if (entries != null) {for (Map.Entryentry : entries) {
sb.append(entry.getKey()).append(Arrays.toString(entry.getValue()));
}
}
}returnsb.toString();
}
}