---
title: "利用Struts2的令牌机制。"
author: "IT009"
date: "2011-10-16T20:32:39Z"
tags: []
categories: ["Web前端"]
slug: "struts2"
draft: false
lastmod: "2011-12-14T00:41:21Z"
id: 1197862
url: "https://it009.iteye.com/blog/1197862"
---

防止表单重复提交主要用的到标签是<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就会不同。
下面用零配置来演示 token的作用
/WEB-INF/content/test-success.jsp

<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
</head>


    <body>
       <s:actionerror/>
       <s:form action="test!save.action" method="POST">
           <s:textfield name="message" label="请输入您的信息"/>
           <s:token name="token"/>
           <s:submit value="确定" />
       </s:form>
    </body>
</html>


/WEB-INF/content/error.jsp


<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body>
<s:actionerror/>
    不能重复提交表单！
</body>
</html>


 

/WEB-INF/content/test-ok.jsp

 

<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
    <body>
       SAVE OK!
    </body>
</html>


TestAction.java

package com.fun.actions;


import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;


import com.opensymphony.xwork2.ActionSupport;
@Results({
@Result(name="invalid.token",location="/index.html",type="redirect")})
@InterceptorRefs({@InterceptorRef(value="token",params={"includeMethods","save"}),@InterceptorRef("defaultStack") })
public class TestAction extends ActionSupport {
    private String message;
    public String execute(){
    return SUCCESS;
    }
    



    public String save(){
    return "ok";
    }
    public String getMessage() {
       return message;
    }
    public void setMessage(String message) {
       this.message = message;
    }
    
}

其实，最主要的就是 token拦截器中还有 includeMethods()这个方法，表示的是，Action中的哪个方法需要经过拦截器。属性excludeMethods（）这个方法表示的是哪个方法不经过拦截器。如果，没有加上“defaultStack”这个拦截器的话，则ActionContext的值将为null。 


http://www.qudong.com/soft/program/jsp/jiqiaoyunyong/20080317/822.html