防止表单的重复提交

思想

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

}
相关推荐
TG_yunshuguoji7 小时前
阿里云代理商:阿里云词元监控与优化
人工智能·阿里云·云计算·token
养肥胖虎2 天前
完整学习LLM(四):Token是什么
大模型·llm·token·学习路线
qcx233 天前
【系统学AI】02 token机制全解:LLM如何‘读懂‘人类语言
人工智能·llm·产品经理·token·费用·deepseek
weixin_553654483 天前
Claude 4.7 的“逻辑美学” vs GPT-5 的“暴力推理”:2026 核心业务代码审计该用谁?
人工智能·gpt·ai·大模型·token
格桑阿sir3 天前
04-大模型智能体开发工程师:Tokenization与模型推理流程
ai·大模型·llm·agent·token·智能体·tokenization
DO_Community6 天前
Token聚合平台 vs 传统云 vs AI原生云,AI推理应用怎么选?
人工智能·agent·token·ai-native·deepseek
创世宇图6 天前
【AI入门知识点】LLM 原理是什么?为什么 ChatGPT 看起来像“会思考”?
人工智能·ai·llm·token
BestOrNothing_20158 天前
VS Code 中 Codex 功能详解:登录、IDE上下文、Token窗口、使用额度与重连问题说明
ide·agent·token·vs code·codex·reconnection
易生一世8 天前
OpenID Connect的认证与授权详解
oauth·jwt·token·openid·pkce
damo王9 天前
极简Agent plan指南
大模型·agent·token·向量模型·open claw·coding plan·agent plan