struts2解决表单重复提交问题方法:
1.在s:form 标签中加入s:token标签
1)会生成一个隐藏域
2)在session中添加一个属性值
3)隐藏域中的值和session中的值是一样的
2.使用token拦截器或者是tokenSession拦截器
这两个拦截器不在默认的拦截器栈中,需要手工配置一下
使用token拦截器,需要配置一个invalid.token的result
使用tokenSession拦截器不用配置任何的result
3.token VS tokenSession
都可以解决表单重复提交问题
如果表单重复提交,token拦截器会跳转到invalid.token这个result
而tokenSession则什么都不会发生
example:
token.jsp页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'token.jsp' starting 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>
<s:form action="token">
<s:textfield name="username" label="username"></s:textfield>
<s:token></s:token>
<s:submit></s:submit>
</s:form>
</body>
</html>
TokenAction类:
package cn.lfd.web.token;
import com.opensymphony.xwork2.ActionSupport;
public class TokenAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public String execute() throws Exception {
System.out.println(username);
return SUCCESS;
}
}
struts.xml配置文件:
<action name="token" class="cn.lfd.web.token.TokenAction">
<interceptor-ref name="tokenSession"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
<result>/success.jsp</result>
<result name="invalid.token">/token-error.jsp</result><!-- 若用的是tokenSession拦截器不用这个result -->
</action>