---
title: "struts2 防止重复提交"
author: "wiseboyloves"
date: "2010-11-14T03:25:26Z"
tags: []
categories: ["企业架构"]
slug: "struts2"
draft: false
lastmod: "2010-11-14T03:27:35Z"
id: 810882
url: "https://wiseboyloves.iteye.com/blog/810882"
---

使用struts2防止用户刷新页面重复提交，做项目经常会用到。

   

struts.xml配置文件如下：

```
<?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="token" namespace="/test" extends="struts-default">
		<action name="token" class="com.cool.token.PersonAction">
			<interceptor-ref name="defaultStack" />
			<interceptor-ref name="token" />
			<result name="invalid.token">/TokenTest.jsp</result> 
			<result name="success">/WEB-INF/page/message.jsp</result> 
		</action>
	</package>
</struts>
```

发生重复提交时，跳转到invalid.token设置的界TokenTest.jsp界面

 

action文件内容如下：

```
package com.cool.token;

import com.opensymphony.xwork2.ActionSupport;

public class PersonAction extends ActionSupport{
	private static final long serialVersionUID = 1L;
	
	private String name;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	public String execute() throws Exception{
		return "success";
	}
}
```

 

 

TokenTest.jsp代码如下：

 

```
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
	<title>Token test</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">
</head>
<body>
	<s:form action="token" namespace="/test" method="post">
		<s:textfield name="name" />
		<s:token/>
		<s:submit />
	</s:form>
</body>
</html>
```

 

比较特殊的就是&lt;s:token /&gt;，运行时客户端value如下，提交时用它的value和服务器端的value来进行比较。

```
<input type="hidden" name="struts.token.name" value="struts.token" />
<input type="hidden" name="struts.token" value="3BSFZGX69PA7NAKG5LCJBM3G7YMDT3EP" />
```

 

 

 /page/message.jsp代码如下：

```
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>Message Page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
  </head>
  <body>
    ${name }
    <%=new Date() %>
  </body>
</html>
```