最近再学struts2。书中讲到struts2的拦截器实现原理,看得一头雾水。几个方法之间循环调用,有点头晕。所以我写了个简化版的程序,理清原理。
Action类,相当于struts2中的action。execute()方法。
public class Action { public String execute(){ System.out.println("action execute()"); return "success"; } }
Interceptor接口(拦截器)。
public interface Interceptor {
String intercept(Invocation invocation);
}
Interceptor的三个实现类:
public class InterceptorA implements Interceptor { @Override public String intercept(Invocation invocation) { System.out.println("A before action"); String result=invocation.invoke(); System.out.println("A after action"); return result; } }public class InterceptorB implements Interceptor { @Override public String intercept(Invocation invocation) { System.out.println("B before action"); String result=invocation.invoke(); System.out.println("B after action"); return result; } }public class InterceptorC implements Interceptor { @Override public String intercept(Invocation invocation) { System.out.println("C execute and return"); return "failed"; } }
Invocation类,相当于ActionInvocation
public class Invocation { private List<Interceptor> interceptors=new ArrayList<>(); private Action action=new Action(); private Iterator<Interceptor> iter; { interceptors.add(new InterceptorA()); interceptors.add(new InterceptorB()); // interceptors.add(new InterceptorC()); iter=interceptors.iterator(); } public String invoke(){ while(iter.hasNext()){ Interceptor interceptor=iter.next(); return interceptor.intercept(this); } return action.execute(); } }运行结果:
A before action B before action action execute() B after action A after action success
如果把注释去掉,运行结果:
A before action B before action C execute and return B after action A after action failed