防止表单数据的重复提交

重复提交的问题:

    * 添加完商品之后,转发到一个页面,刷新该页面.

    * 网速很慢,点击提交的按钮,其实已经在提交了但是网速慢,不停的点击提交.

解决重复提交的根本解决办法:令牌机制(一次性).

    * 生成随机的令牌保存在session中.

    * 在表单的提交的时候,将随机的令牌放入到表单的隐藏字段中.

    * 在Servlet中获得session中和表单中的令牌是否一致.将令牌销毁.

    * 如果一致执行插入操作,不一致跳转到其他页面.

jsp表单页面中:

<%
    String token = UUID.randomUUID().toString();
    request.getSession().setAttribute("token", token);
%>
<body>
    <h1></h1>
    <form action="${ pageContext.request.contextPath }/Add" method="post">
        <input type = "hidden" name = "token" value="${ sessionScope.token }"/>

servlet中:

     request.setCharacterEncoding("utf-8");
        String token = request.getParameter("token");
        String token1 = (String)request.getSession().getAttribute("token");
        request.getSession().removeAttribute("token");
        if (!token1.equals(token)) {
            request.getRequestDispatcher("/msg.jsp").forward(request, response);
            return;
        }
原文地址:https://www.cnblogs.com/laodang/p/9505937.html