struts2 源码分析

以下代码模拟Struts2的interceptor实现

附件是struts2源码分析

1. 定义接口
public interface Interceptor
{
String intercept(ActionInvocation invocation) throws Exception;
}


2.接口实现

public class InterceptorA implements Interceptor
{
@Override
public String intercept(ActionInvocation invocation) throws Exception
{
System.out.println("begin A");
invocation.invoke();
System.out.println("before interceptor's resultCode : " + invocation.getResultCode());
System.out.println("end A");
return "A";
}

}


public class InterceptorB implements Interceptor
{
@Override
public String intercept(ActionInvocation invocation) throws Exception
{
System.out.println("begin B");
invocation.invoke();
System.out.println("before interceptor's resultCode : " + invocation.getResultCode());
System.out.println("end B");
return "B";
}
}


public class InterceptorC implements Interceptor
{

@Override
public String intercept(ActionInvocation invocation) throws Exception
{
System.out.println("begin C");
invocation.invoke();
System.out.println("before interceptor's resultCode : " + invocation.getResultCode());
System.out.println("end C");
return "C";
}
}



3.Invoke 调用

public class ActionInvocation
{

Iterator<Interceptor> InterceptorIterator = null;
private String resultCode = null;
protected boolean executed = false;
public String invoke()
{

if (executed)
{
throw new IllegalStateException("Action has already executed");
}
if (InterceptorIterator.hasNext())
{
Interceptor interceptor = InterceptorIterator.next();
try
{
resultCode = interceptor.intercept(ActionInvocation.this);
}
catch (Exception e)
{
e.printStackTrace();
}
}
return "fuck";
}

public Iterator<Interceptor> getIt()
{
return InterceptorIterator;
}

public void setIt(Iterator<Interceptor> it)
{
this.InterceptorIterator = it;
}

public Iterator<Interceptor> getInterceptorIterator()
{
return InterceptorIterator;
}

public void setInterceptorIterator(Iterator<Interceptor> interceptorIterator)
{
InterceptorIterator = interceptorIterator;
}

public String getResultCode()
{
return resultCode;
}

public void setResultCode(String resultCode)
{
this.resultCode = resultCode;
}

}




4 调用
 public static void main(String[] args)
{
ActionInvocation invocation = new ActionInvocation();

List<Interceptor> list = new ArrayList<Interceptor>();
Interceptor a = new InterceptorA();
Interceptor b = new InterceptorB();
Interceptor c = new InterceptorC();
list.add(a);
list.add(b);
list.add(c);
Iterator<Interceptor> it = list.iterator();
invocation.setIt(it);
invocation.invoke();
System.out.println("end");

}


运行结果:

begin A
begin B
begin C
before interceptor's resultCode : null
end C
before interceptor's resultCode : C
end B
before interceptor's resultCode : B
end A
end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值