struts2-Token Interceptor(处理表单重复提交)
令牌提交
默认栈里面没有,手动添加
1 <!-- 配置默认执行的拦截器栈,增加令牌拦截器 --> 2 <interceptors> 3 <interceptor-stack name="tokenStack"> 4 <interceptor-ref name="defaultStack" /> 5 <interceptor-ref name="token" > 6 <!-- 配置令牌拦截器,拦截的方法名,如果配置多个方法时,用","隔开 --> 7 <param name="includeMethods">save,update</param> 8 </interceptor-ref> 9 </interceptor-stack> 10 </interceptors>
如何处理表单重复提交
1、定义一个jsp页面
在jsp页面增加一个隐藏域<s:token></s:token>
1 <s:form name="form1" namespace="/model" action="userAction_update" method="post" theme="simple"> 2 用户名:<s:textfield name="username"/><br> 3 电话:<s:textfield name="tel" /><br> 4 描述:<s:textfield name="des" /><br> 5 <s:token></s:token> 6 <s:submit type="submit" value="保存"></s:submit> 7 </s:form>
2、定义struts_token.xml配置文件
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE struts PUBLIC 3 "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" 4 "http://struts.apache.org/dtds/struts-2.3.dtd"> 5 <struts> 6 <package name="model" namespace="/model" extends="struts-default"> 7 8 <!-- 配置默认执行的拦截器栈,增加令牌拦截器 --> 9 <interceptors> 10 <interceptor-stack name="tokenStack"> 11 <interceptor-ref name="defaultStack" /> 12 <interceptor-ref name="token" > 13 <!-- 配置令牌拦截器,拦截的方法名,如果配置多个方法时,用","隔开 --> 14 <param name="includeMethods">save,update</param> 15 </interceptor-ref> 16 </interceptor-stack> 17 </interceptors> 18 19 <default-interceptor-ref name="tokenStack" /> 20 21 <action name="userAction_*" class="cn.zengfansheng.model.UserAction" method="{1}"> 22 <result name="add">/model/add.jsp</result> 23 <result name="edit">/model/edit.jsp</result> 24 <result name="success">/model/success.jsp</result> 25 <!-- 配置表单重复提交后,要转向到的页面,配置加入了“invalid.token”结果,在会话的token与请求的token不一致时,将会直接返回“invalid.token”结果--> 26 <result name="invalid.token">/model/error.jsp</result> 27 </action> 28 </package> 29 </struts>
3、配置struts.xml文件
1 <include file="cn/zengfansheng/struts/model/struts_model.xml"></include>
4、error.jsp页面打印错误信息
1 error.jsp页面如下:使用<s:actionerror/>打印错误信息 2 3 <%@ page language="java" pageEncoding="utf-8" contentType="text/html; charset=utf-8"%> 4 <%@ taglib uri="/struts-tags" prefix="s"%> 5 <html> 6 <head> 7 <title>My JSP 'index.jsp' starting page</title> 8 </head> 9 <body> 10 <s:actionerror/> 11 </body> 12 </html>
by hacket