防止反复提交 struts2 token
为了防止反复提交,我们要用token进行处理,即令牌
struts2对token进行了封装,所以变的特别简单:
1.jsp页面
1.引入struts2标签:<%@ taglib uri="/struts-tags" prefix="s"%>
2.在form表单里,添加一句话<s:token/>
Action不用作处理
2.在struts.xml配置文件里
<action name="test" class="test.Test">
<result name="invalid.token">/pages/false.jsp</result>
<result name="success">/pages/success.jsp</result>
<interceptor-ref name="defaultStack" />
<interceptor-ref name="token" />
</action>
解释:<result name="invalid.token">/pages/false.jsp</result> 如果反复提交了,就跳到false.jsp页面
<result name="success">/pages/success.jsp</result> 如果正确提交,跳到success.jsp页面
<interceptor-ref name="defaultStack" /> <!-- 这两句话是有关token配置的 拦截器-->
<interceptor-ref name="token" />
“token”拦截器在会话token与请求token不一致时,将会直接返回“invalid.token”结果。
eg:
jsp页面:
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <%@ taglib uri="/struts-tags" prefix="s"%> 3 <% 4 String path = request.getContextPath(); 5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 6 %> 7 8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 9 <html> 10 <head> 11 <base href="<%=basePath%>"> 12 13 <title>My JSP 'test.jsp' starting page</title> 14 15 <meta http-equiv="pragma" content="no-cache"> 16 <meta http-equiv="cache-control" content="no-cache"> 17 <meta http-equiv="expires" content="0"> 18 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 19 <meta http-equiv="description" content="This is my page"> 20 <!-- 21 <link rel="stylesheet" type="text/css" href="styles.css"> 22 --> 23 24 </head> 25 26 <body> 27 This is my JSP page. <br> 28 <form action="test.action"> 29 <s:token/> 30 <input type="submit" value="提交" /> 31 </form> 32 </body> 33 </html>
Action:
1 package test; 2 3 import com.opensymphony.xwork2.ActionSupport; 4 5 public class Test extends ActionSupport{ 6 7 public String execute() throws Exception { 8 9 return SUCCESS; 10 } 11 12 }
struts.xml:
1 <action name="test" class="test.Test"> 2 <result name="invalid.token">/pages/false.jsp</result> 3 <result name="success">/pages/test.jsp</result> 4 5 <interceptor-ref name="defaultStack" /> 6 <interceptor-ref name="token" /> 7 </action>
struts2 :token的原理:http://www.cnblogs.com/iyangyuan/archive/2013/05/05/3060488.html
浙公网安备 33010602011771号