防止表单的重复提交
表单重复提交的原因:网络延迟,重新加载
表单重复提交的解决办法:前端js控制,后端用token+session来控制(增加程序的容错性)
1、前端用js来进行校验
<%@ 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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登陆页面</title>
</head>
<script type="text/javascript">
var flag = false;//标识是否提交过.true代表已经提交,false代表没有提交
function isSubmit(){
if(flag){
//已经提交过了
return false;
}else{
//没有提交过,提交一次
flag = true;
return true;
}
}
</script>
<body>
<form action="/cookie-demo/loginServlet" method="post" onsubmit="return isSubmit();">
用户: <input type="text" name="username"/>
<input type="submit" value="登陆">
</form>
</body>
</html>
效果演示
2、后端通过token+session来进行校验,为了展示效果,展示去掉前端代码
一、前端代码
<%@ 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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登陆页面</title>
</head>
<body>
<form action="/cookie-demo/loginServlet" method="post">
<input type="hidden" name="token" value="${token }"/>
用户: <input type="text" name="username"/>
<input type="submit" value="登陆">
</form>
</body>
</html>
2、产生token令牌的servlet
/**
* 通过UUID随机产生一个token令牌
* @author 紫炎易霄
*/
@WebServlet("/tokenServlet")
public class TokenServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//通过UUID生成token令牌,并转发到jsp中,存储到隐藏域里面
String token = UUID.randomUUID().toString();
HttpSession session = req.getSession();
session.setAttribute("token", token);
req.getRequestDispatcher("/login.jsp").forward(req, resp);
}
}
3、处理用户请求的servlet
/**
* 接收表单重复提交
* @author 紫炎易霄
*/
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//防止乱码
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=utf-8");
//接收页面传过来的参数
String username = req.getParameter("username");
String paramToken = req.getParameter("token");
HttpSession session = req.getSession();
String token = (String) session.getAttribute("token");
if(token != null && token.equals(paramToken)){
//移除session
session.removeAttribute("token");
//说明是第一次提交
//休眠5秒钟
try {
System.out.println(username+"执行数据库插入操作!!!!");
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
resp.getWriter().write("数据保存成功!");
}else{
resp.getWriter().write("您已经提交过了,请不要再重复提交!");
}
}
}
效果演示