servlet一般防止表单重复提交

页面----------------------------------

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'token.jsp' starting page</title>
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
  </head>
 
  <body>
    <%
        //生成一个formhash,算法可以自己定,不随便重复就可以了
        Random ran = new Random();
        String formhash = String.valueOf(ran.nextInt());
        //读取当前session里面的hashCode集合,此处使用了Set,方便判断。
        Set<String> formhashSession = (Set<String>) session.getAttribute("formhashSession");
        if (formhashSession == null) {
             formhashSession = new HashSet<String>();
        }
        // 检测重复问题
        while (formhashSession.contains(formhash)) {
             formhash = String.valueOf(ran.nextInt());
        }
        // 保存到session里面
        formhashSession.add(formhash);
        // 保存
        session.setAttribute("formhash", formhashSession);
     %>
    <form action="/tokenWeb/TokenServlet">
     <input type="hidden" name="formhash" id="formhash" value="<%=formhash%>" />
     <input type="submit" value="提交" />
    </form>
  </body>
</html>

-------------------------servlet-----------------------------------

 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  try {
   HttpSession session=request.getSession();
   String formhash = request.getParameter("formhash");
   // 拿到session里面的集合
         Set<String> formhashSession = (Set<String>) session.getAttribute("formhash");
          // 如果没有,则是重复提交,或者非法提交
         Thread.sleep(2000);
         if (formhashSession == null || !formhashSession.contains(formhash) ) {
                System.out.println("重复提交!");
          }else{
           System.out.println("正常");
          }
           // 最后,如果操作成功,从session里面把这个formhash 删掉!
          formhashSession.remove(formhash);
          session.setAttribute("formhashSession", formhashSession);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }

 

转载于:https://my.oschina.net/chenliyong/blog/675920

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值