---
title: "防止用户重复提交的方法"
author: "windpoplar"
date: "2017-02-19T22:38:46Z"
tags: []
categories: ["互联网"]
slug: "untitled"
draft: false
lastmod: "2017-02-19T22:38:46Z"
id: 2357934
url: "https://windpoplar.iteye.com/blog/2357934"
---

表单重复提交是在多用户Web应用中最常见、带来很多麻烦的一个问题。有很多的应用场景都会遇到重复提交问题，比如：

点击提交按钮两次。 点击刷新按钮。 使用浏览器后退按钮重复之前的操作，导致重复提交表单。 使用浏览器历史记录重复提交表单。 浏览器重复的HTTP请求。

　　几种防止表单重复提交的方法

　　**1.禁掉提交按钮**。表单提交后使用Javascript使提交按钮disable。这种方法防止心急的用户多次点击按钮。但有个问题，如果客户端把Javascript给禁止掉，这种方法就无效了。

　　我之前的文章曾说过用一些Jquery插件效果不错。

　　**2.Post/Redirect/Get模式**。在提交后执行页面重定向，这就是所谓的Post-Redirect-Get (PRG)模式。简言之，当用户提交了表单后，你去执行一个客户端的重定向，转到提交成功信息页面。

　　这能避免用户按F5导致的重复提交，而其也不会出现浏览器表单重复提交的警告，也能消除按浏览器前进和后退按导致的同样问题。

　　**3.在session中存放一个特殊标志**。当表单页面被请求时，生成一个特殊的字符标志串，存在session中，同时放在表单的隐藏域里。接受处理表单数据时，检查标识字串是否存在，并立即从session中删除它，然后正常处理数据。

　　如果发现表单提交里没有有效的标志串，这说明表单已经被提交过了，忽略这次提交。

　　这使你的web应用有了更高级的XSRF保护。

　　**4.在数据库里添加约束。**在数据库里添加唯一约束或创建唯一索引，防止出现重复数据。这是最有效的防止重复提交数据的方法。

 

\----------------------------------

[spring mvc 防止重复提交表单的两种方法，推荐第二种](http://blog.csdn.net/u013378306/article/details/52944780)

# 第一种方法：判断session中保存的token

原理：在新建页面中Session保存token随机码，当保存时验证，通过后删除，当再次点击保存时由于服务器端的Session中已经不存在了，所有无法验证通过。

 

1.新建注解：

 

```
/**
 * <p>
 * 防止重复提交注解，用于方法上<br/>
 * 在新建页面方法上，设置needSaveToken()为true，此时拦截器会在Session中保存一个token，
 * 同时需要在新建的页面中添加
 * <input type="hidden" name="token" value="${token}">
 * <br/>
 * 保存方法需要验证重复提交的，设置needRemoveToken为true
 * 此时会在拦截器中验证是否重复提交
 * </p>
 * @author: chuanli
 * @date: 2013-6-27上午11:14:02
 *
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AvoidDuplicateSubmission {
    boolean needSaveToken() default false;
    boolean needRemoveToken() default false;
}
```

 

 

2\. 新建拦截器

 

```
/**
 * <p>
 * 防止重复提交过滤器
 * </p>
 *
 * @author: chuanli
 * @date: 2013-6-27上午11:19:05
 */
public classAvoidDuplicateSubmissionInterceptorextendsHandlerInterceptorAdapter{
    private static final Logger LOG = Logger.getLogger(AvoidDuplicateSubmissionInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception {

        User user = UserUtil.getUser();
        if (user != null) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();

            AvoidDuplicateSubmission annotation = method.getAnnotation(AvoidDuplicateSubmission.class);
            if (annotation != null) {
                boolean needSaveSession = annotation.needSaveToken();
                if (needSaveSession) {
                    request.getSession(false).setAttribute("token", TokenProcessor.getInstance().generateToken());
                }

                boolean needRemoveSession = annotation.needRemoveToken();
                if (needRemoveSession) {
                    if (isRepeatSubmit(request)) {
                        LOG.warn("please don't repeat submit,[user:" + user.getUsername() + ",url:"
                                + request.getServletPath() + "]");
                        return false;
                    }
                    request.getSession(false).removeAttribute("token");
                }
            }
        }
        return true;
    }

    private boolean isRepeatSubmit(HttpServletRequest request) {
        String serverToken = (String) request.getSession(false).getAttribute("token");
        if (serverToken == null) {
            return true;
        }
        String clinetToken = request.getParameter("token");
        if (clinetToken == null) {
            return true;
        }
        if (!serverToken.equals(clinetToken)) {
            return true;
        }
        return false;
    }

}
```

 

 

3\. 在Spring中配置

 

```
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
   <propertyname="interceptors"><list><beanclass="com.sohu.tv.crm.aop.UserLogInterceptor"/><beanclass="com.sohu.tv.crm.aop.AvoidDuplicateSubmissionInterceptor"/></list></property></bean>
```

 

 

4\. 在相关方法中加入注解：

 

```
@RequestMapping("/save")
 @AvoidDuplicateSubmission(needRemoveToken = true)
    public synchronized ModelAndView save(ExecutionUnit unit, HttpServletRequest request, HttpServletResponse response)
            throws Exception {

@RequestMapping("/edit")
    @AvoidDuplicateSubmission(needSaveToken = true)
    public ModelAndView edit(Integer id, HttpServletRequest request) throws Exception {
```

 

5.在新建页面中加入

                &lt;input type="hidden" name="token" value="${token}"&gt;

注意在ajax提交时 要加上 formToken参数

## 第二种方法（判断请求url和数据是否和上一次相同）

**推荐，非常简单，页面不需要任何传入，只需要在验证的controller方法上写上自定义注解即可**

写好自定义注解

 

**\[java]** [view plain](http://blog.csdn.net/u013378306/article/details/52944780 "view plain") [copy](http://blog.csdn.net/u013378306/article/details/52944780 "copy")

 

 [![在CODE上查看代码片](https://code.csdn.net/assets/CODE_ico.png)](https://code.csdn.net/snippets/1951802 "在CODE上查看代码片")[![派生到我的代码片](https://code.csdn.net/assets/ico_fork.svg)](https://code.csdn.net/snippets/1951802/fork "派生到我的代码片")

01. package com.thinkgem.jeesite.common.repeat\_form\_validator;
02. import java.lang.annotation.ElementType;
03. import java.lang.annotation.Retention;
04. import java.lang.annotation.RetentionPolicy;
05. import java.lang.annotation.Target;
06. /\**
07. * 一个用户 相同url 同时提交 相同数据 验证
08. * @author Administrator
09. \*
10. \*/
11. @Target(ElementType.METHOD)
12. @Retention(RetentionPolicy.RUNTIME)
13. public @interface SameUrlData {
14. }

 

写好拦截器

 

**\[java]** [view plain](http://blog.csdn.net/u013378306/article/details/52944780 "view plain") [copy](http://blog.csdn.net/u013378306/article/details/52944780 "copy")

 

 [![在CODE上查看代码片](https://code.csdn.net/assets/CODE_ico.png)](https://code.csdn.net/snippets/1951802 "在CODE上查看代码片")[![派生到我的代码片](https://code.csdn.net/assets/ico_fork.svg)](https://code.csdn.net/snippets/1951802/fork "派生到我的代码片")

01. package com.thinkgem.jeesite.common.repeat\_form\_validator;
02. import java.lang.reflect.Method;
03. import java.util.HashMap;
04. import java.util.Map;
05. import javax.servlet.http.HttpServletRequest;
06. import javax.servlet.http.HttpServletResponse;
07. import org.springframework.web.method.HandlerMethod;
08. import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
09. import com.thinkgem.jeesite.common.mapper.JsonMapper;
10. /\**
11. * 一个用户 相同url 同时提交 相同数据 验证
12. * 主要通过 session中保存到的url 和 请求参数。如果和上次相同，则是重复提交表单
13. * @author Administrator
14. \*
15. \*/
16. public class SameUrlDataInterceptor  extends HandlerInterceptorAdapter{
17. @Override
18. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
19. if (handler instanceof HandlerMethod) {
20. HandlerMethod handlerMethod = (HandlerMethod) handler;
21. Method method = handlerMethod.getMethod();
22. SameUrlData annotation = method.getAnnotation(SameUrlData.class);
23. if (annotation != null) {
24. if(repeatDataValidator(request))//如果重复相同数据
25. return false;
26. else
27. return true;
28. }
29. return true;
30. } else {
31. return super.preHandle(request, response, handler);
32. }
33. }
34. /\**
35. * 验证同一个url数据是否相同提交  ,相同返回true
36. * @param httpServletRequest
37. * @return
38. \*/
39. public boolean repeatDataValidator(HttpServletRequest httpServletRequest)
40. {
41. String params=JsonMapper.toJsonString(httpServletRequest.getParameterMap());
42. String url=httpServletRequest.getRequestURI();
43. Map&lt;String,String&gt; map=new HashMap&lt;String,String&gt;();
44. map.put(url, params);
45. String nowUrlParams=map.toString();//
46. Object preUrlParams=httpServletRequest.getSession().getAttribute("repeatData");
47. if(preUrlParams==null)//如果上一个数据为null,表示还没有访问页面
48. {
49. httpServletRequest.getSession().setAttribute("repeatData", nowUrlParams);
50. return false;
51. }
52. else//否则，已经访问过页面
53. {
54. if(preUrlParams.toString().equals(nowUrlParams))//如果上次url+数据和本次url+数据相同，则表示城府添加数据
55. {
56. return true;
57. }
58. else//如果上次 url+数据 和本次url加数据不同，则不是重复提交
59. {
60. httpServletRequest.getSession().setAttribute("repeatData", nowUrlParams);
61. return false;
62. }
63. }
64. }
65. }

 

配置spring mvc

 

**\[html]** [view plain](http://blog.csdn.net/u013378306/article/details/52944780 "view plain") [copy](http://blog.csdn.net/u013378306/article/details/52944780 "copy")

 

 [![在CODE上查看代码片](https://code.csdn.net/assets/CODE_ico.png)](https://code.csdn.net/snippets/1951802 "在CODE上查看代码片")[![派生到我的代码片](https://code.csdn.net/assets/ico_fork.svg)](https://code.csdn.net/snippets/1951802/fork "派生到我的代码片")

1. &lt;mvc:interceptor&gt;
2. &lt;mvc:mapping path="/\*\*"/&gt;
3. &lt;bean class="com.thinkgem.jeesite.common.repeat\_form\_validator.SameUrlDataInterceptor"/&gt;
4. &lt;/mvc:interceptor&gt;

[![](http://static.blog.csdn.net/images/save_snippets.png)]()

[]()