http://blog.chinaunix.net/uid-26642709-id-3061264.htmlhtml
使用session token時,必須用struts2表標籤庫,不能用html
經過session token防止重複提交:
當客戶端請求頁面時,服務器會經過token標籤生成一個隨機數,而且將隨機數放置到session當中,而後將隨機數發向客戶端;若是客戶第一次提交,那麼瀏覽器會將該隨機數發往服務器,服務器端會接收到該隨機數而且與session中所保存的隨機數進行比較,這時二者的值是相同的,服務器認爲是第一次提交,而且將更新服務器端的這個隨機數值;若是此時再次重複提交,那麼客戶端向服務器端的隨機數仍是以前的那個,而服務器端的隨機數則已經發生了變化,二者不一樣,服務器就認爲這事重複提交,進而轉向invalid.token所指向的結果頁面。
token.jsp
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<
%@taglib prefix = "s" uri= "/struts-tags" %>
<body>
<s:form action = "token.action" theme = "simple">
username: <s:textfield name = "username"></s:textfield><br>
password:<s:password name = "password"></s:password><br>
<s:token></s:token>
<s:submit value = "submit "></s:submit>
</s:form>
</body>
</html>
struts.xml
<action name = "token" class = "com.shengsiyuan.struts2.TokenAction">
<result name = "success">/tokenSuccess.jsp</result>
<result name = "invalid.token">tokenFail.jsp</result> <!-- 次是不時input,算是特例 -->
<interceptor-ref name = "token"></interceptor-ref>
<interceptor-ref name= "defaultStack"></interceptor-ref>
</action>
TokenAction.java
package com.shengsiyuan.struts2;
import com.opensymphony.xwork2.ActionSupport;
public class TokenAction extends ActionSupport
{
private String username ;
private String password ;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String execute() throws Exception {
return SUCCESS ;
}
}
tokenSuccess.jsp
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<
%@taglib prefix = "s" uri = "/struts-tags" %>
<html>
<body>
username:<s:property value = "username"/><br>
password:<s:property value = "password"/>
</body>
</html>
tokenFail.jsp
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%> <body> 不用重複提交表單 </body> </html>