防止表單重複提交主要用的到標籤是<s: token />,攔截器 <interceptor-ref name="token" />,還有一個默認的返回值<result name="invalid.token">/input.jsp</result>
在頁面加載時,<s: token />產生一個GUID(Globally Unique Identifier,全局惟一標識符)值的隱藏輸入框如:
- <input type="hidden" name="struts.token.name" value="struts.token"/>
- <input type="hidden" name="struts.token" value="BXPNNDG6BB11ZXHPI4E106CZ5K7VNMHR"/>
同時,將GUID放到會話(session)中;在執行action以前,「token」攔截器將會話token與請求token比較,若是二者相同,則將會話中的token刪除並往下執行,不然向actionErrors加入錯誤信息。如此一來,若是用戶經過某種手段提交了兩次相同的請求,兩個token就會不一樣。
如下爲action代碼
import com.opensymphony.xwork2.ActionSupport;
public
class TestAction
extends ActionSupport {
private
static
final
long serialVersionUID = 6820659617470261780L;
private String message;
public String getMessage() {
return message;
}
public
void setMessage(String message) {
this.message = message;
}
@Override
public String execute() {
System.out.println(
"Executing action, your message is " + message);
return SUCCESS;
}
}
再看看JSP的寫法
<
%@ page
language
="java"
contentType
="text/html; charset=utf-8"
pageEncoding
="utf-8" %
>
<
%@ taglib
prefix
="s"
uri
="/struts-tags" %
>
<
!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>
<
html
xmlns
="http://www.w3.org/1999/xhtml"
>
<
head
>
<
title
>struts2 test token
</title>
<
s:head
/>
</head>
<
body
>
<
s:actionerror
/>
<
s:form
action
="testAction"
>
<
s:textfield
name
="message"
label
="Message"
/>
<
s:token
/>
<
%-- 注意這裏--%
>
<
s:submit
/>
</s:form>
</body>
</html>
下面是struts2的配置文件
<?
xml
version
="1.0"
encoding
="UTF-8"
?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<
struts
>
<
package
name
="test"
extends
="struts-default"
namespace
="/testToken"
>
<
action
name
="test"
class
="com.fhx.TestAction"
>
<
result
name
="invalid.token"
>/input.jsp
</
result
>
<
result
>/input.jsp
</
result
>
<
interceptor-ref
name
="defaultStack"
/>
<
interceptor-ref
name
="token"
/>
</
action
>
</
package
>
</
struts
>
以上XML片斷值注意的是加入了「token」攔截器和「invalid.token」結果,由於「token」攔截器在會話token與請求token不一致時,將會直接返回「invalid.token」結果。