首页 > 代码库 > Struts2.3.20使用token防表单重复提交:警告: Could not find token name in params.

Struts2.3.20使用token防表单重复提交:警告: Could not find token name in params.

警告: Could not find token name in params.

就是这么一个小小的错误,浪费了我好多时间,在网上看了好多帖子,都是扯淡的帖子,要么说你没放置<s:token />要么说你这个没放置到<form>中,还有就是说你拦截器顺序不对,都胡扯吧啦,没说到点子上,我在此给出解决方案:你的Action类要继承ActionSupport,否则就会出现这样的错误!

另外上一些标准的模板:
前台JSP:
 <s:debug></s:debug>
 <s:form action="TokenAction" method="post">
  <s:textfield name="username" label="username"></s:textfield>
  <s:submit label="提交"></s:submit>
  <s:token />
 </s:form>
注意添加:<%@ taglib prefix="s" uri="/struts-tags"%>
后台Action:
package cn.edu.shu.second.form.token;
import com.opensymphony.xwork2.ActionSupport;
public class TokenAction extends ActionSupport {
 private String username;
 public String getUsername() {
  return username;
 }
 public void setUsername(String username) {
  this.username = username;
 }
 public String execute() {
  try {
   Thread.sleep(1000);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  System.out.println("休息了一秒咯");
  return "success";
 }
}

还有一个Struts.xml:
  <action name="TokenAction" class="cn.edu.shu.second.form.token.TokenAction">
   <interceptor-ref name="token" />
   <interceptor-ref name="defaultStack" />
   <result name="invalid.token">error.jsp</result>
   <result name="success">success.jsp</result>
  </action>
注意我这个是标准配置,别听网上扯淡,什么拦截器放在result之后,什么默认拦截器放在token之前,总结一个字就是扯淡,给出证据,我们来看Struts官方文档给出的Example:

Extending the interceptor:

While not very common for users to extend, this interceptor is extended by the TokenSessionStoreInterceptor. The handleInvalidToken(com.opensymphony.xwork2.ActionInvocation) andhandleValidToken(com.opensymphony.xwork2.ActionInvocation) methods are protected and available for more interesting logic, such as done with the token session interceptor.

Example code:

 <action name="someAction" class="com.examples.SomeAction">
     <interceptor-ref name="token"/>
     <interceptor-ref name="basicStack"/>
     <result name="success">good_result.ftl</result>
 </action>

 <-- In this case, myMethod of the action class will not
        get checked for invalidity of token -->
 <action name="someAction" class="com.examples.SomeAction">
     <interceptor-ref name="token">
        <param name="excludeMethods">myMethod</param>
     </interceptor-ref name="token"/>
     <interceptor-ref name="basicStack"/>
     <result name="success">good_result.ftl</result>
 </action>

Struts2.3.20使用token防表单重复提交:警告: Could not find token name in params.