防止表单的重复提交

思想

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

}
相关推荐
FungLeo1 天前
NodeJS Koa 后端用户会话管理,JWT, Session,长短Token,本文一次性讲明白
jwt·token·session·会话管理·cookies
Le_ee4 天前
dvwa7——SQL Injection
数据库·sql·网络安全·靶场·token·dvwa
zwjapple7 天前
react-native的token认证流程
react native·状态模式·token
测试工程喵16 天前
如何测试JWT的安全性:全面防御JSON Web Token的安全漏洞
前端·网络·功能测试·安全·json·接口测试·token
测试工程喵17 天前
Token类型与用途详解:数字身份的安全载体图谱
功能测试·安全·接口测试·模块测试·token·登录认证·token类型
纪伊路上盛名在19 天前
LLM大语言模型系列1-token
字符编码·人工智能·语言模型·自然语言处理·token·文本处理
仙人掌_lz2 个月前
利用python从零实现Byte Pair Encoding(BPE):NLP 中的“变形金刚”
开发语言·python·gpt·自然语言处理·llm·token·deepseek
绘绘~3 个月前
jenkins配置连接k8s集群
java·docker·kubernetes·jenkins·token·hhtps
码农研究僧3 个月前
UniApp 中封装 HTTP 请求与 Token 管理(附Demo)
vue3·uniapp·js·token·request
南城巷陌5 个月前
node.js中实现token的生成与验证
前端·node.js·token