防止表单的重复提交可以从2个方面考虑:
1、在JSP界面设置javascript,在点击submit按钮后,使按钮失效
2、再提交成功后,重定向到某个页面,防止反复提交某个表单(但该种方式受制于网络传输的因素)
下面介绍第三种方法:
1、JSP界面
<body>
<%
String s1 = UUID.randomUUID().toString(); //设置UUID
String s2 = s1;
pageContext.setAttribute("s2", s2,pageContext.SESSION_SCOPE); //设置session级别的UUID
pageContext.setAttribute("s1", s1);
%>
<form action="/mytest/servlet/recommit" method="post">
<input type="hidden" name = "formuuid" value=${pageScope.s1}> //隐式提交表单的UUID
用户名:<input type="text" name="username" ><br>
密码:<input type="password" name="password" ><br>
<input type="submit" id = "sub1" value="提交">
</form>
<script type="text/javascript">
window.οnlοad=function(){
document.getElementById("sub1").οnclick=function(){
document.forms[0].submit();
document.getElementById("sub1").disabled=true;
}
}
</script>
</body>
2、sevlet控制比对Session的UUID和表单的UUID
import java.io.IOException;
import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/servlet/recommit")
public class Recommit extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//在提交前设置4秒的延时,模拟网络延时
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
request.setCharacterEncoding("UTF-8");
response.setHeader("content-Type","text/html;charset=utf-8");
//获取表单及session的提交信息
String str1 = request.getParameter("username");
String str2 = request.getParameter("password");
String str3 = request.getParameter("formuuid");
String str4 = (String) request.getSession().getAttribute("s2");
String str5 =(String) request.getSession().getAttribute("s3");
//System.out.println(str3+"-----"+str4+"-------"+str5);
//判断表单及Session中的UUID是否一致
if(str3.equals(str4)) {
System.out.println(str1+"_"+str2);
str5 = str4;
//将session中的信息保存到到其他的值中,下次再次刷新表单提交的时候给予友好提示用
request.getSession().setAttribute("s3", str5);
//表单真确提交,则删除session中的UUID值,防止重复提交
request.getSession().removeAttribute("s2");
}else if(str3.equals(str5)){ //判断是否是多次刷新,给予友好提示
response.getWriter().write("请不要重复提交表单");
}else{
System.out.println("错误表单提交");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}