防止表单的重复提交

思想

  1. 打开页面时,生成一个token,将这个token保存到Session中,
  2. 在表单中提供一个隐藏域,设置其值为每1步中生成的token
  3. 在处理表单的Servlet中,获取表单隐藏域中的token与Session中的token进行比较,比较完之后直接将Session中的token删除
    • 如果相等可以提交,
    • 如果不相等,提示用户不能重复提交

示例

打开页面的Servlet

java 复制代码
@WebServlet("/open")
public class OpenServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	  		//生成唯一的令牌
  		String token = UUID.randomUUID().toString();
  		//将生成的令牌放到Session中
  		request.getSession().setAttribute("token", token);
  		//
  		response.sendRedirect("demo.jsp");
	}
}

页面 demo.jsp

html 复制代码
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<html>
  <head>
    <title>防止表单的重复提交</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">
  </head>
  <body>
    <form action="${pageContext.request.contextPath}/demo/deal" method="post">
    	<input type="hidden" name="token" value="${sessionScope.token}"/>
    	<input type="submit" value="提交"/>
    </form>
  </body>
</html>

处理表单请求的Servlet

java 复制代码
@WebServlet("/deal")
public class DealServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String fToken = request.getParameter("token");//隐藏域中的令牌
		HttpSession session = request.getSession();
		String sToken = (String) session.getAttribute("token");
		
		//检查令牌
		if(fToken.equals(sToken)){
			//把令牌从HttpSession中删除掉
			session.removeAttribute("token");
		}else{
			response.getWriter().write("请不要重复提交请求");
		}
	}

}
相关推荐
XLYcmy12 小时前
小红书 算法一面 十一
google·meta·llm·负载均衡·token·moe·glam
小七-七牛开发者1 天前
dsh 拆解系列 Vol.01:没有特权内核的 Agent 运行时
ai·大模型·agent·claude·token·工作流·skill·claudecode·ai coding
孙启超2 天前
【大模型应用开发】LLM 到底是什么,以及它是怎么训练的
人工智能·lora·llm·微调·sft·token·rlhf
小七-七牛开发者2 天前
Agent 小知识|Agent 环境工程:部分可观测性、状态转移与执行隔离
ai·大模型·agent·claude·token·工作流·skill·claudecode·ai coding
番茄不是西红柿kk3 天前
什么是Token?
人工智能·ai·chatgpt·agent·token·codex·deepseek
赵大仁4 天前
Prompt 缓存与上下文压缩:把 Token 账单砍一刀的实操清单
ai·大模型·prompt·token·成本优化
SoStraw6 天前
webrpc 常见问题 FAQ:无公网 IP、Token、传文件,以及和 frp / WebRTC 的差别
tcp/ip·webrtc·frp·token·faq·webrpc·无公网ip
小当家.10510 天前
Token成本控制实战:语义缓存、上下文压缩与工具缓存
java·spring·缓存·token·上下文
小七-七牛开发者10 天前
Codex 实践系列 Vol.04:用 Goal 和 Plan 管住一个长任务
ai·大模型·agent·claude·token·工作流·claudecode·ai coding