使用Struts实现防止表单重复提交

来源:互联网 发布:http 411 nginx 编辑:程序博客网 时间:2024/04/30 08:51

 首先知道引起表单重复提交的原因有2个

1: 当用户提交了一个表单,此时,如果跳转时使用dispatcher,则地址栏显示的是处理这个表单的Action的地址,若此时刷新,则会重新发送一次表单数据,即又进行了一次提交,若这个Action是用来处理用户注册的,那么重复提交会再一次向数据库中插入之前已经插入的数据,这显然不是我们想要的。

2. 服务器处理时间久。当用户在表单中填完信息,点击“提交”按钮后,由于服务器反应时间过长没能及时看到响应信息,或者出于其它目的,再次点击“提 交”按钮,从而导致在服务器端接收到两条或多条相同的信息。

 知道了这2个原因,那么 有两种方法,可以防止表单重复提交,一种是用Action的重定向,一种是用Session Token(Session令牌)。但在实际中需要吧这2中情况都考虑才行:

Login.jsp:    <s:form action="login" theme="simple">    username:<s:textfield name="username"></s:textfield><br>    password:<s:password name="password"></s:password><br>    <s:submit value="submit"></s:submit>    <s:token></s:token><!--一定要有这个标签-->    </s:form>
struts.xml<span style="white-space:pre"></span><action name="login" class="loginAction" method="login"><interceptor-ref name="tokenStack"></interceptor-ref><result name="invalid.token">/WEB-INF/error/error.jsp</result><!-- 这里用redirect防止在刷新时造成重复提交表单的问题 --><result name="success" type="redirectAction">/manage_empty</result><result name="input" type="redirect">/index.jsp</result></action>
这里还要配置相应的拦截器:

<span style="white-space:pre"></span><interceptors><interceptor-stack name="tokenStack"><interceptor-ref name="token" /><interceptor-ref name="defaultStack" /></interceptor-stack></interceptors>




0 0
原创粉丝点击