1.编写RepeatSubmit注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RepeatSubmit{}
2.注册RepeatSubmitInterceptor继承HandlerInterceptorAdapter
public abstract class RepeatSubmitInterceptor extends HandlerInterceptorAdapter {}
3.通过handlerMethod判断方法上是否存在RepeatSubmit,如果有,说明该方法需要验证重复提交
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class);
if (annotation != null)
{
if (this.isRepeatSubmit(request))
{
AjaxResult ajaxResult = AjaxResult.error("不允许重复提交,请稍后再试");
ServletUtils.renderString(response, JSON.marshal(ajaxResult));
return false;
}
}
return true;
} else {
return super.preHandle(request, response, handler);
}
}
验证表单重复提交方法:
public abstract boolean isRepeatSubmit(HttpServletRequest request) throws Exception;
4.通过request获取方法参数和请求地址
String nowParams = JSON.marshal(request.getParameterMap());
Map<String, Object> nowDataMap = new HashMap<String, Object>();
nowDataMap.put(REPEAT_PARAMS, nowParams);
nowDataMap.put(REPEAT_TIME, System.currentTimeMillis());
// 请求地址(作为存放session的key值)
String url = request.getRequestURI();
5.从session中获取repeatData缓存数据
HttpSession session = request.getSession();
Object repeatDataSessionObj = session.getAttribute(SESSION_REPEAT_KEY);
6.通过当前的请求地址从repeatData缓存数据获取 上一次请求的 preRequestData
if (repeatDataSessionObj != null)
{
Map<String, Object> sessionMap = (Map<String, Object>) repeatDataSessionObj;
if (sessionMap.containsKey(url))
{
Map<String, Object> preDataMap = (Map<String, Object>) sessionMap.get(url);
if (compareParams(nowDataMap, preDataMap) && compareTime(nowDataMap, preDataMap))
{
return true;
}
}
}
7.判断 上一次的请求系统时间 与 当前请求的系统时间 间隔 是否在 限制 提交范围内。
private boolean compareTime(Map<String, Object> nowMap, Map<String, Object> preMap) {
long time1 = (Long) nowMap.get(REPEAT_TIME);
long time2 = (Long) preMap.get(REPEAT_TIME);
if ((time1 - time2) < (this.intervalTime * 1000))
{
return true;
}
return false;
}
8.比较 preRequestData中的请求参数 与 当前的请求参数是否一致(可以对请求参数进行序列化)
private boolean compareParams(Map<String, Object> nowMap, Map<String, Object> preMap) {
String nowParams = (String) nowMap.get(REPEAT_PARAMS);
String preParams = (String) preMap.get(REPEAT_PARAMS);
return nowParams.equals(preParams);
}
9.结合 7和8的判断,做出对应策略,如果重复,返回重复提交提示。不重复则 放行。
RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class);
if (annotation != null)
{
if (this.isRepeatSubmit(request))
{
AjaxResult ajaxResult = AjaxResult.error("不允许重复提交,请稍后再试");
ServletUtils.renderString(response, JSON.marshal(ajaxResult));
return false;
}
}
return true;