攔截器是動態攔截Action調用的對象。它提供了一種機制可以使開發者可以定義在一個action執行的前後執行的代碼,也可以在一個action執行前阻止其執行。同時也是提供了一種可以提取action中可重用的部分的方式。
- init(FilterConfig filterConfig),
- destroy(),
- doFilter(ServletRequest request, ServletResponse response, FilterChain chain)。
if (intexrceptors.hasNet()) {Interceptor interceptor=(Interceptor)interceptors.next();resultCode = interceptor.intercept(this);} else {if (proxy.getConfig().getMethodName() == null) {resultCode = getAction().execute();} else {resultCode = invokeAction(getAction(), proxy.getConfig());}}
1)攔截器接口
public interface MyInterceptor { public void inteceptor(Invocation invocation) ; } <span style="font-size:18px;"><span style="font-size:12pt"> </span></span>
2)攔截器兩個實現類
<span style="font-size:18px;">public class FirstInterceptor implements MyInterceptor { public void inteceptor(Invocation invocation) { System.out.println("第一個攔截器開始。。。。"); //調用invoke方法 invocation.invoke() ; System.out.println("第一個攔截器結束......."); } } public class SecondInterceptor implements MyInterceptor { public void inteceptor(Invocation invocation) { System.out.println("第二個攔截器開始....."); //調用invoke方法 invocation.invoke() ; System.out.println("第二個攔截器結束......"); } }<span style="font-size:12pt"> </span></span>
3)Action
<span style="font-size:18px;">public class Action { public String execute() { System.out.println("執行execute方法"); return null ; } }</span>
4)控制器
<span style="font-size:18px;">public class Invocation { List<MyInterceptor> interceptors = new ArrayList<MyInterceptor>(); int index = -1; public Invocation() { //需要執行的攔截器 this.interceptors.add(new FirstInterceptor()); this.interceptors.add(new SecondInterceptor()); } public void invoke() { index++; if (index < interceptors.size()) { //一次調用攔截器的inteceptor方法 interceptors.get(index).inteceptor(this); } else { //攔截器攔截完畢後執行action new Action().execute(); } } } </span>
5)攔截器入口
<span style="font-size:18px;"> public static void main(String[] args) { //struts2的攔截器入口就是invoke方法 new Invocation().invoke() ; }</span>