struts2的action执行过程模拟

package xwork;

import java.io.Serializable;

/**
 * @author wangmingjie
 * @date 2008-9-26上午11:09:05
 */
public interface Interceptor extends Serializable {
    String intercept(ActionInvocation invocation) throws Exception;
}
==============================================

package xwork;
/**
 * @author wangmingjie
 * @date 2008-9-26上午11:11:56
 */
public class FirstInterceptor implements Interceptor {

 public String intercept(ActionInvocation invocation) throws Exception {
  String resultCode = null;
  System.out.println("before first Interceptor ");
  resultCode = invocation.invoke();
  System.out.println("after first Interceptor ");
  return resultCode;
 }

}
==============================================

package xwork;
/**
 * @author wangmingjie
 * @date 2008-9-26上午11:13:34
 */
public class SecondInterceptor implements Interceptor {

 public String intercept(ActionInvocation invocation) throws Exception {
  String resultCode = null;
  System.out.println("before second Interceptor ");
  resultCode = invocation.invoke();
  System.out.println("after second Interceptor ");
  return resultCode;
 }

}

==================核心调用过程============================

package xwork;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author wangmingjie
 * @date 2008-9-26上午11:10:00
 */
public class ActionInvocation {
 private boolean  executed = false;
 private String resultCode = null;
 private Iterator interceptors;
 private void init(){
        List<Interceptor> interceptorList = new ArrayList<Interceptor>();
        interceptorList.add(new FirstInterceptor());
        interceptorList.add(new SecondInterceptor());
        interceptors = interceptorList.iterator();
 }
 
 public String invoke() throws Exception {
  if(executed){
   throw new Exception("已经执行了");
  }
  if (interceptors.hasNext()) {//下面就是核心实现代码
   resultCode = ((Interceptor)interceptors.next()).intercept(ActionInvocation.this);//注意这里,将自己作为参数传入,这是一种递归的调用方法。
  } else {
   resultCode = "success";//执行action的方法
   System.out.println("执行action");
  }
  
  if (!executed) {
   System.out.println("执行preResultListener");
   executed = true;
  }
  return null;
 }
 
 public static void main(String[] args) throws Exception{
  //再进行断点跟踪一下。
  ActionInvocation ai = new ActionInvocation();
  ai.init();
  ai.invoke();
 }
 
}

================执行结果如下==============================

before first Interceptor
before second Interceptor
执行action
执行preResultListener
after second Interceptor
after first Interceptor
=========================================================

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值