struts2使用攔截器來檢查表單是否重復(fù)提交,它采用同步令牌的方式來實(shí)現(xiàn)對表單重復(fù)提交的判斷。
首先需要在表單中使用<s:token name="user.token"></s:token>
<s:token>標(biāo)簽創(chuàng)建一個新的令牌值,并用你所指定的令牌名把令牌保存到session中。而這個令牌值是隨即產(chǎn)生的經(jīng)過加密的字符序列,不會重復(fù)。struts2使用攔截器來檢查表單是否重復(fù)提交,它采用同步令牌的方式來實(shí)現(xiàn)對表單重復(fù)提交的判斷。
首先需要在表單中使用
其次需要為action配置TokenInterceptor或者TokenSessionStoreInterceptor攔截器。這兩個攔截器都已經(jīng)在struts-default.xml中定義,但沒有包含在defaultStack攔截器棧中。
在action中配置攔截器和在重復(fù)提交時,將要請求導(dǎo)向的結(jié)果視圖。
<action name="register" class="com.zhaosoft.action.RegisterAction">
<!-- 配置異常映射,當(dāng)RegisterAction拋出Exception異常時,向用戶顯示error.jsp頁面 -->
<exception-mapping result="error" exception="java.lang.Exception"/>
<result name="invalid.token">/WEB-INF/pages/register.jsp</result>
<result name="input">/WEB-INF/pages/register.jsp</result>
<result name="success">/WEB-INF/pages/success.jsp</result>
<result name="error">/WEB-INF/pages/error.jsp</result>
<interceptor-ref name="defaultStack">
<param name="workflow.excludeMethods">default</param>
</interceptor-ref>
<interceptor-ref name="token">
<param name="excludeMethods">default</param>
</interceptor-ref>
</action>
注:excludeMethods指定要排除的方法。
在register.jsp頁面中添加action級別的錯誤信息顯示的標(biāo)簽:<s:actionerror/>
在form中添加<s:token>標(biāo)簽:<s:token name="user.token"></s:token>
最好為在資源文件中設(shè)置鍵struts.messages.invalid.token的本地化消息。
struts.messages.invalid.token=您已經(jīng)提交了表單,請不要重復(fù)提交。
TokenSessionStoreInterceptor:使用TokenSessionStoreInterceptor攔截器同樣能避免重復(fù)提交,TokenSessionStoreInterceptor集成自TokenInterceptor。使用TokenSessionStoreInterceptor將不會輸出任何錯誤信息。如果token無效,請求被導(dǎo)向到invalid.token結(jié)果碼映射的視圖。
配置如下:
<interceptor-ref name="tokenSession">
<param name="excludeMethods">default</param>
</interceptor-ref>