轉載聲明:本文從博客園copy而來
原帖網址:http://www.cnblogs.com/SeaSky0606/p/4643194.html
前言:
接觸Struts2已經有一段時間,Student核心內容就是通過攔截器對接Action,實現View層的控制跳轉。本文根據自身理解對Struts2進行一個Java實例的模擬,方便大家理解!
示意圖
通過以上簡單的示意圖,我們可以看到Struts2將ServletAPI與業務處理分離,讓開發者能夠在用戶向客戶端發送請求的時候通過攔截機制更好的進行業務層處理,提高開發效率。下面我們就通過幾個Java類模擬Struts2攔截器的實現。
攔截原理
代碼設計:
- 1ActionInvocation
package com.simulink; import java.util.ArrayList; import java.util.List; public class AntionInvocation { Action a = new Action(); int index = -1; List<Interceptor> interceptors = new ArrayList<Interceptor>(); public AntionInvocation() { interceptors.add(new FirstInterceptor()); interceptors.add(new SecondInterceptor()); } public void invoke() { index++; // System.out.println("index:" + index); if (index >= this.interceptors.size()) { a.execute(); } else { this.interceptors.get(index).intercept(this); } } }
- FirstInterceptor類
package com.simulink; public class FirstInterceptor implements Interceptor { @Override public void intercept(AntionInvocation invocation) { System.out.println(-1); invocation.invoke(); System.out.println(1); } }
- SecondInterceptor類
package com.simulink; public class SecondInterceptor implements Interceptor { @Override public void intercept(AntionInvocation invocation) { System.out.println(-2); invocation.invoke(); System.out.println(2); } }
- Action類
package com.simulink; public class Action { public void execute(){ System.out.println("execute!"); } }
- 5測試類Main
package com.simulink; public class Main { /** * @param args */ public static void main(String[] args) { new AntionInvocation().invoke(); } }
輸出結果:
-1 -2 execute! 2 1
後記:接觸過WebWork的朋友應該會發覺struts2跟其很相似,實際上Struts2就是Struts1和WebWork的結合體。其主要技術大部分來自WebWork!