2010年1月1日金曜日

struts2 重复提交拦截器用法 token与token-session

首先要在jsp的from标签里加入防重复提交标签, 生成如下的内容:(struts.token.name 标识哪个隐藏域存了 token 值)


注意自定义的表单域别重名了。它的作用是防止表单重复提交,每次加载页面 struts.token 的值都不一样,如果两次提交时该值一样,则认为是重复提交。此时要启用 TokenInterceptor(token) 拦截器,最好是也启用 TokenSessionStoreInterceptor(token-session) 拦截器,不然后台会出现错误提示:

2008-11-17 20:39:21 com.opensymphony.xwork2.interceptor.ParametersInterceptor setParameters
严重: ParametersInterceptor - [setParameters]: Unexpected Exception catched: Error setting expression 'struts.token' with value '[Ljava.lang.String;@1c2e163'
2008-11-17 20:39:21 com.opensymphony.xwork2.interceptor.ParametersInterceptor setParameters
严重: ParametersInterceptor - [setParameters]: Unexpected Exception catched: Error setting expression 'struts.token.name' with value '[Ljava.lang.String;@abaf8c'

但不影响使用。不过如果只有 token-session 拦截器却是不行的。

token 和 token-session 拦截器的启用,是在 struts.xml 配置文件中,既可以为包启用,也可以单独为某个 action 启用:

1) 为包启用 token 和 token-session











/login.jsp
/exception.jsp

............................................................................

2) 为 Action 启用 token 和 token-session





/login.jsp
/exception.jsp


............................................................................


注意 token、token-session 和 defaultStack 的顺序要保证,还需要加上名为 "invalid.token" 的 result,当发现重复提交时转向到这个逻辑页,如 /exception.jsp,在 /exception.jsp 加上 在出现重复提交时就会提示:The form has already been processed or no token was supplied, please try again.


token: 在活动中检查合法令牌(token), 防止表单的重复提交;
token-session: 同上, 但是在接到非法令牌时将提交的数据保存在session中;

0 件のコメント: