利用Struts2的令牌机制。

防止表单重复提交主要用的到标签是<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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值