附件是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