表单重复提交的问题
表单的重复提交:
若刷新表单页面,再提交表单不算重复提交。
在不刷新表单页面的前提下:
多次点击提交按钮、
已经提交成功,按 “回退” 之后,再点击 “提交按钮”。
在控制器响应页面的形式为转发情况下,若已经提交成功,然后点击 "刷新(F5)“。
重复提交的缺点:
加重了服务器的负担,可能导致错误操作。
struts的解决方法
I. 在 s:form 中添加 s:token 子标签
> 生成一个隐藏域
> 在 session 添加一个属性值
> 隐藏域的值和 session 的属性值是一致的.
<s:token>
标签要配合token或tokenSession拦截器
II. 使用 Token 或 TokenSession 拦截器.
> 这两个拦截器均不在默认的拦截器栈中, 所以需要手工配置一下
> 若使用 Token 拦截器, 则需要配置一个 token.valid 的 result
> 若使用 TokenSession 拦截器, 则不需要配置任何其它的 result
III. Token VS TokenSession
> 都是解决表单重复提交问题的
> 使用 token 拦截器会转到 token.valid 这个 result
> 使用 tokenSession 拦截器则还会响应那个目标页面, 但不会执行 tokenSession 的后续拦截器. 就像什么都没发生过一样!
IV. 可以使用 s:actionerror 标签来显示重复提交的错误消息.
该错误消息可以在国际化资源文件中覆盖. 该消息可以在 struts-messages.properties 文件中找到
struts.messages.invalid.token=The form has already been processed or no token was supplied, please try again。
验证
@Override
public String execute() throws Exception {
System.out.println("TokenTestAction.execute\t"+name);
TimeUnit.SECONDS.sleep(2);
return SUCCESS;
}
用延时达到网络阻塞的效果。
1.如果只在jsp页面上加了<s:token></s:token>
标签,但没有引用token或tokenSesson拦截器,那么就会有下面的异常
<s:debug></s:debug>
<s:form action="tokenTest" namespace="/" method="POST">
<s:token></s:token>
<s:textfield name="name" label="Name"></s:textfield>
<s:submit></s:submit>
</s:form>
12:43:27.723 [http-nio-8080-exec-10] ERROR com.opensymphony.xwork2.interceptor.ParametersInterceptor - Developer Notification (set struts.devMode to false to disable this message):
Unexpected Exception caught setting 'token' on 'class com.example.action.TokenTestAction: Error setting expression 'token' with value ['NNR1FKQSFW003MOSH48IIHPHJPIA7IHG', ]
TokenTestAction.execute 艾克
12:43:28.327 [http-nio-8080-exec-2] ERROR com.opensymphony.xwork2.interceptor.ParametersInterceptor - Developer Notification (set struts.devMode to false to disable this message):
Unexpected Exception caught setting 'token' on 'class com.example.action.TokenTestAction: Error setting expression 'token' with value ['NNR1FKQSFW003MOSH48IIHPHJPIA7IHG', ]
TokenTestAction.execute 艾克
12:43:29.191 [http-nio-8080-exec-1] ERROR com.opensymphony.xwork2.interceptor.ParametersInterceptor - Developer Notification (set struts.devMode to false to disable this message):
Unexpected Exception caught setting 'token' on 'class com.example.action.TokenTestAction: Error setting expression 'token' with value ['NNR1FKQSFW003MOSH48IIHPHJPIA7IHG', ]
TokenTestAction.execute 艾克
2.如果给action配置了token拦截器
配置了token拦截器的同时,还要给invalid.token
属性赋值,就是跳转到token-error.jsp页面。
只有一次异常,也就是说重复的提交被拦截了。
3.给action配置tokenSession
拦截器
不用多配置result。