表单重复提交问题解决办法
程序员文章站
2022-04-03 08:26:55
...
一、出现表单重复提交的原因
(1)网络延迟
(2)重新加载
(3)回退之后又返回之前页面进行提交
二、解决问题的办法
(1)从前台解决:控制提交事件只触发一次
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Form表单</title>
</head>
<script>
var flag = false;//false表示未提交,true表示已提交
function isSubmited(){
if(!flag){//未提交
flag = true;//修改标识为已提交标识
return true;//通过
}
return false;//因为已提交,所以拒绝提交
}
</script>
<body>
<form action="${pageContext.request.contextPath}/DoFormServlet" method="post" onsubmit="return isSubmited()">
用户名:<input type="text" name="username">
<input type="submit" value="提交" id="submit">
</form>
</body>
</html>
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/saveServlet")
public class test extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("数据插入数据库操作");
resp.setContentType("text/html;charset=UTF-8");
resp.getWriter().println("保存成功");
}
}
(2)从后台解决
上一篇: 鲁元公主是刘邦的独女,她最后的结局如何?