1.struts 防止表单重复提交 2. 拦截器

1. 使用struts 防止表单提交 时, form 表单必须使用struts标签库编写,如<s:form/> 等,而不是html标签  

2. 拦截器是struts2的核心。  interceptor接口

package com.interceptor;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

/**
 * 1. 实现interceptor接口
 * 2. struts.xml 配置 interceptors 拦截器
 * 3. 在struts.xml action中 配置 interceptor-ref 使用
* 4. set 方法会在init 方法前执行 *
@author Administrator * */ public class Myinterceptor implements Interceptor{    private String test;
  //getter 和setter 方法
@Override public void destroy() { } 
@Override
public void init() { } // test 的初始化会在 init 前
@Override
public String intercept(ActionInvocation arg0) throws Exception {
  System.out.println("before");
  return arg0.invoke();
  System.out.println("after");
}
}
<interceptors>
            <interceptor name="theInteceptor" class="com.interceptor.Myinterceptor">
          <param name="test">12</param>
        </
interceptor>
        
        <interceptor name="theInteceptor2" class="com.interceptor.StrutsInterceptor">
          <param name="test">12</param>
        </interceptor>


        </interceptors>
        
        
        
        <global-exception-mappings>
            <exception-mapping result="globalerror" exception="Exception"></exception-mapping>
        </global-exception-mappings>
        <global-results>
            <result name="globalerror">/index.jsp</result>
        </global-results>
        
        <action name="login" class="com.login.Login">
            <result name="success">/index.jsp</result>
            <!-- action 错误 调整 -->
            <exception-mapping result="error" exception="com.exception.Myexception"></exception-mapping><!-- 可以自定义错误类型 -->
            <result name="error">/index.jsp</result>
            
            <interceptor-ref name="theInteceptor"></interceptor-ref>  <!--如果指定了自定义拦截器,defaultstack 就不起作用了。
          需要将defaultstack拦截器添加到自定义拦截器后,否则struts2的一些功能可能不起作用-->
<interceptor-ref name="theInteceptor2"></> </action>
      <!--调用该action 拦截器的执行 输出 顺序是 before ,inteceptor before, inteceptor after,after ... 拦截器默认拦截的是action的execute 方法
        那么如何拦截自定义方法呢??需要用到方法拦截器MethodFilterInterceptor: includeMethods,excludeMethods 指定方法名,如果某个方法在两个里面都
        有的话,includeMethods 级别更高,所以会拦截。 实现MethodFilterInterceptor ,重写doInterceptor 方法
       -->
package com.interceptor;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * struts 拦截器 ,,通常是实现 AbstractInterceptor, 而不是直接实现Interceptor 接口
 * @author Administrator
 *
 */

public class StrutInterceptor extends AbstractInterceptor{

    @Override
    public String intercept(ActionInvocation arg0) throws Exception {
        System.out.println("interceptor before");
        String result=arg0.invoke();//invoke()指 拦截器完成后继续执
        System.out.println("interceptor after");
        return result;
    }

}
原文地址:https://www.cnblogs.com/zhangchenglzhao/p/3710447.html