使用struts2的token机制和cookie来防止表单重复提交

今天在做一个投票系统时要实现防止表单重复提交!

当时就想到了用struts2提供的token机制

struts2的token机制防止表单重复提交:

首先需要在提交的jsp页面(要使用token机制,必须使用struts2提供的标签库)加上

<s:token></s:token>  

这段代码,然后在struts.xml里面需要进行如下配置:

复制代码
    <action name="token" class="com.xiaoluo.struts2.TokenAction">  
        <result name="success">/tokenSuccess.jsp</result>  
        <result name="invalid.token">/tokenFail.jsp</result> //name必须是invalid.token  
                  
        <interceptor-ref name="token"></interceptor-ref>  
        <interceptor-ref name="defaultStack"></interceptor-ref>  
    </action>  
复制代码

总的来说,struts2提供的token机制来防止表单重复提交还是挺方便的,但是有时却不一定很好的达到我们所需要的目的!

接下来是用cookie来防止表单重复提交,就拿今天做的投票系统的例子来说,通过将 每个投票选项的id以及"hasVote" + id的组合放到cookie里面,然后根据所需设置cookie存活时间,然后放到response里面,然后在处理投票的action里首先判断 cookie中的name是否是已经投过票的名称,如果是就重定向到重复提交页面!

复制代码
    Cookie[] cookies = request.getCookies();  
                  
        for(Cookie cookie : cookies)  
        {  
            if(String.valueOf(vote.getId()).equals(cookie.getValue()))  
            {  
                response.sendRedirect("repeatSubmit.jsp");  
            }  
            else  
            {  
                Cookie cookie2 = new Cookie("hasVote" + vote.getId(), String.valueOf(vote.getId()));  
                          
                response.addCookie(cookie2);  
            }  
        }  
复制代码

我觉得cookie的这种方法更加实用一些,在实际中根据自己情况自行选择方式吧!

原文地址:https://www.cnblogs.com/zhaolizhe/p/6936496.html