防止表单的重复提交

思想

  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 天前
doubao-seed-2-1 系列模型上架算桥 API | 多模态理解能力继续加强!
人工智能·api·token·算力租赁·算力平台
玩AI的奶茶3 天前
配一次环境像装修一次房:哪些云 GPU 平台能把它留下来?
人工智能·ai·gpu算力·token·算力租赁
ifenxi爱分析4 天前
爱分析发布2026年Token市场海外对标研究报告
token
知无不研11 天前
调用模型的API接口与Token详谈
ai·agent·token·api接口
XLYcmy12 天前
大语言模型(LLM)核心技术梳理:从词元化到 RAG 的工程实践
自然语言处理·prompt·embedding·token·cot·tokenization·上下文工程
szephyr12 天前
前端鉴权实战:Token 存哪、怎么刷新、怎么防 XSS 与 CSRF
鉴权·xss·csrf·jwt·token
csdn_aspnet13 天前
.NetCore Webapi 接口验证请求来源
.netcore·ip·token·签名·webapi·cors·sign
丿Wayne13 天前
iOS Token 刷新实战(Actor 避免并发重复刷新)
ios·swift·token·actor·swift并发
花北城14 天前
【C#底层库】access_token授权鉴权验证
c#·鉴权·token·授权
七夜zippoe14 天前
Agent 上下文工程:Token 管理、上下文压缩与分层记忆设计
ai·agent·token·上下文压缩·分层记忆