package com.tch.test.struts2.interceptor;
import java.util.Iterator;
import java.util.List;
public class ActionInvocation {
private List<Interceptor> interceptors;
private Iterator<Interceptor> iterator;
public void invoke(){
if(hasNext()){
getInterceptor().intercept(this);
}else{
System.out.println("调用action方法");
}
}
Interceptor getInterceptor(){
return iterator.next();
}
private boolean hasNext() {
return iterator.hasNext();
}
public List<Interceptor> getInterceptors() {
return interceptors;
}
public void setInterceptors(List<Interceptor> interceptors) {
this.interceptors = interceptors;
this.iterator = interceptors.iterator();
}
}
package com.tch.test.struts2.interceptor;
public interface Interceptor {
void intercept(ActionInvocation invocation);
}
package com.tch.test.struts2.interceptor;
public class FirstInterceptor implements Interceptor {
@Override
public void intercept(ActionInvocation invocation) {
System.out.println("begin >>> first...");
invocation.invoke();
System.out.println("end <<< first");
}
}
package com.tch.test.struts2.interceptor;
public class SecondInterceptor implements Interceptor {
@Override
public void intercept(ActionInvocation invocation) {
System.out.println("begin >>> second...");
invocation.invoke();
System.out.println("end <<< second");
}
}
package com.tch.test.struts2.interceptor;
public class ThirdInterceptor implements Interceptor {
@Override
public void intercept(ActionInvocation invocation) {
System.out.println("begin >>> third...");
invocation.invoke();
System.out.println("end <<< third");
}
}
package com.tch.test.struts2.interceptor;
public class FourthInterceptor implements Interceptor {
@Override
public void intercept(ActionInvocation invocation) {
System.out.println("begin >>> fourth...");
invocation.invoke();
System.out.println("end <<< fourth");
}
}
package com.tch.test.struts2.interceptor;
import java.util.ArrayList;
import java.util.List;
public class TestInterceptor {
public static void main(String[] args) {
List<Interceptor> interceptors = new ArrayList<Interceptor>();
FirstInterceptor first = new FirstInterceptor();
SecondInterceptor second = new SecondInterceptor();
ThirdInterceptor third = new ThirdInterceptor();
FourthInterceptor fourth = new FourthInterceptor();
interceptors.add(first);
interceptors.add(second);
interceptors.add(third);
interceptors.add(fourth);
ActionInvocation invocation = new ActionInvocation();
invocation.setInterceptors(interceptors);
invocation.invoke();
}
}
OK。。。
本文深入探讨了Struts2框架中拦截器的工作原理,通过实例展示了如何使用拦截器来扩展Action方法的行为,包括引入多个拦截器并定义它们的执行顺序。详细介绍了拦截器接口、具体拦截器类(如FirstInterceptor、SecondInterceptor、ThirdInterceptor和FourthInterceptor)以及如何在ActionInvocation类中设置和调用拦截器。

1115

被折叠的 条评论
为什么被折叠?



