struts2的攔截器棧調用模擬

轉載聲明:本文從博客園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!

-------- 以上內容純屬個人學習總結,不代表任何團體或單位。若有理解不到之處請見諒!---------
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章