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

来源:互联网 发布:在线服装搭配软件 编辑:程序博客网 时间:2024/06/06 04:05

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);
                 其它的处理代码
         }

原创粉丝点击