六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 36|回复: 0

Struts 1.x | 通过stuts中的Token(令牌)阻止页面重复提交

[复制链接]

升级  40.67%

33

主题

33

主题

33

主题

秀才

Rank: 2

积分
111
 楼主| 发表于 2013-2-7 16:10:56 | 显示全部楼层 |阅读模式
通过stuts中的Token(令牌)阻止页面重复提交


     1)原理:



                    当客户端每次请求一个页面之前,服务器端会产生一个令牌,同时把这个令牌传给客户端
                    之后再进行处理。处理完毕之后,马上更新旧的令牌,同时传送旧的令牌给客户端。
                    这样如果客户端提交表单一次之后,按IE上的后退按钮再次提交时,就会发出客户端的
                    令牌(因为是以前的令牌)与现在服务器的令牌不一致。通过这个就能判断是否重复提交
                    表单

     2)步骤:



             1) jsp页面放一个超链接 <a href="prepareAction.do">发表留言</a>
             2) 点击超链接之后跳转到prepareAction,在prepareAction里面去添加一个令牌
                    public ActionForward execute(ActionMapping mapping, ActionForm form,
                                      HttpServletRequest request, HttpServletResponse response) { 
 
                         this.saveToken(request);
                         return mapping.findForward("2");             //跳到2.jsp页面 
                     }
               prepareAction实际上是过度用的一个Action目的是为了添加令牌
              3) 在2.jsp里面一般是一个表单用来填写数据,并提交到另外一个insertTalkAction里面 实现真正的插入
                       <html:form action="insertTalkAction.do">
                               留言id  <html:text property="uid"/><br>
                               内容     <html:text property="content"/><br>
                        <html:submit>提交</html:submit>    
                       </html:form>

             4) 在insertTalkAction里面的代码是关键代码 
                  public ActionForward execute(ActionMapping mapping, ActionForm form,
                                                          HttpServletRequest request, HttpServletResponse response) {  
                      if (this.isTokenValid(request,true)) { //没有重复提交
                              Random rnd=new Random();     
                              int n=rnd.nextInt(2000)+900;
                              request.setAttribute("msg", "没有重复提交,将插入数据..");
                              String sql=String.format("insert into emp(empno,ename) values(%d,'小上')", n);
                              dbManager.RunNoneResultSql(sql);  
                       }  else {        //重复提交了  
                               request.setAttribute("msg", "重复提交!!!!");
                               this.saveToken(request);
                       }
                       return mapping.findForward("msg");
                 }
  ===========================一般的格式======================

         if (isTokenValid(request, true)) { //表单不是重复提交
                这里是保存数据的代码
         } else  {  //表单重复提交
                 saveToken(request);
                 其它的处理代码
         }
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表