防止表单的重复提交

思想

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

}
相关推荐
庞轩px3 天前
JWT + Redis 双 Token 机制:从原理到实战
数据库·redis·缓存·jwt·token·登录认证
胡耀超4 天前
Token的八副面孔:为什么“词元“不需要更好的翻译,而需要更多的读者
大数据·人工智能·python·agent·token·代币·词元
村中少年5 天前
vscode如何添加ollama本地模型-实现token自由
vscode·llm·token·ollama·本地模型·qwen3
happymaker06266 天前
深入了解会话跟踪技术、过滤器、EL、JSTL
web开发·token·cookie·session·el·jstl
lpfasd1237 天前
OpenRouter低延迟使用中国Token算力
网络·token
JavaGuide7 天前
万字拆解 LLM 运行机制:Token、上下文与采样参数
ai·llm·prompt·ai编程·token
七夜zippoe14 天前
OpenClaw 会话管理:单聊、群聊、多模型
大数据·人工智能·fastapi·token·openclaw
阿昭L16 天前
说说Windows进程的令牌(token)
windows·系统安全·token
૮・ﻌ・18 天前
Node.js - 04:MongoDB、会话控制
数据库·mongodb·node.js·jwt·token·cookie·session
蜡台18 天前
整合一些 免费甚至无限量token平台,方便OpenClaw 使用,及一些相关使用配置代码
nvidia·token·ollama·openrouter·openclaw·龙虾