防止表单的重复提交

思想

  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("请不要重复提交请求");
		}
	}

}
相关推荐
理人综艺好会2 天前
双Token机制在实际项目中的应用与实践
中间件·token
XLYcmy4 天前
一个基于 Python 的轻量级 LLM(大语言模型)API 客户端程序:从API交互到LLM应用架构
服务器·python·ai·llm·prompt·agent·token
小七-七牛开发者6 天前
AI Agent 的 4 个工程关键词:Prompt、Context、Loop、Harness 到底是什么?
ai·大模型·agent·token·context·loop·codex·harness
ZorChi8 天前
AI API 调用优化实战:统一入口与超时处理指南
人工智能·aigc·接口·api·agent·token·中转站
极连AI10 天前
国产大模型譬如DeepSeek接入codex教程分享
人工智能·gpt·chatgpt·api·token·极连ai·zovelox.com
摸鱼同学13 天前
LLM 是什么?从 API 调用到 Token 机制
ai·大模型·llm·token·claudecode
阿昌喜欢吃黄桃14 天前
大模型常见参数学习笔记
人工智能·ai·llm·prompt·token
abigale0315 天前
LangChain 实践4: 7个人AI助手全栈项目:完整拆解+分阶段开发指南
缓存·langchain·prompt·token·rag·lcel
xixixi7777720 天前
Token 经济重构价值分配:中国移动成核心枢纽,算网安一体化按需计费普惠中小企业
人工智能·ai·大模型·云计算·算力·token·流量
TG_yunshuguoji21 天前
阿里云代理商:阿里云词元监控与优化
人工智能·阿里云·云计算·token