2012-03-31 37 views
2

我在Struts2的Struts 2:有多少次,如果其配置爲一個Action類

有一個問題關於攔截

Struts2提供了非常強大的控制使用攔截的請求的機制的攔截器會被調用。攔截器負責大部分請求處理。它們在調用動作之前和之後由控制器調用,因此它們位於控制器和動作之間。攔截器執行任務,如日誌記錄,驗證,文件上傳,雙後衛等提交

我採取這種以上線路由:

http://viralpatel.net/blogs/2009/12/struts2-interceptors-tutorial-with-example.html

在這個例子中,你將看到如何在執行動作之前和之後調用攔截器,以及如何將結果呈現給用戶。

我採取這種以上線路從

http://www.vaannila.com/struts-2/struts-2-example/struts-2-interceptors-example-1.html

我寫了一個基本的攔截器,並將其插入到我的Action類:

public class InterceptorAction implements Interceptor { 
    public String intercept(ActionInvocation invocation) throws Exception { 
     System.out.println("Action class has been called : "); 
     return success; 
    } 
} 

struts.xml的

<action name="login" class="com.DBAction"> 
    <interceptor-ref name="mine"></interceptor-ref> 
    <result name="success">Welcome.jsp</result> 
    <result name="error">Login.jsp</result> 
</action> 

按從他們的網站上面的陳述,我認爲這條線Action類被稱爲是在控制檯上的兩倍(這是行動Action類之前和之後),但它已被印只有一次?

請讓我知道,如果我的理解是錯誤的,或者作者是錯在該網站?

+0

短版四元數的回答:攔截器不是「兩次調用」,攔截包裹的動作調用,就像一個Servlet過濾器「包圍「一個servlet請求。唯一的「難題」是結果已經由時間控制返回到攔截器呈現出來;如果你想在結果呈現之前做某些事情,你必須實現一個'PreResultListener'。 – 2012-03-31 18:40:24

+0

謝謝戴夫,那是有用的信息。 – Pawan 2012-03-31 19:18:40

回答

5

不花時間閱讀網頁的時候可以清楚一些事情了......

你缺少你攔截了重要的一步。

Struts2,使用一個名爲的對象ActionInvocation來管理調用攔截器。

讓我們給ActionInvocation的名稱(調用),並顯示該框架如何啓動球滾動:

ActionInvocation invocation; 
invocation.invoke(); //this is what the framework does... this method then calls the first interceptor in the chain. 

現在我們知道攔截器可以做前處理和後處理......但是接口只定義一種做攔截器工作的方法(init和delete只是生命週期)!如果界面定義了doBefore和doAfter,那麼這很容易,所以必定會有一些魔法,發生......

事實證明,您負責在控制器的某個位置將控制權交還給動作調用。這是一項要求。如果你不把控制權交給ActionInvocation,你會打破這個鏈條。

所以創建一個攔截器,當你執行以下步驟

  1. 創建一個實現com.opensymphony.xwork2.interceptor.Interceptor
  2. [可選]做預處理工作
  3. 呼叫ActionInvocations類調用方法繼續處理堆棧並捕獲返回值。
  4. [可選]隨着上述呼叫展開進行後處理。
  5. 返回步驟3(結果字符串)中的字符串,除非您有其他理由。

這裏是一個完整的,但很沒用例如:

package com.quaternion.interceptors; 

import com.opensymphony.xwork2.ActionInvocation; 
import com.opensymphony.xwork2.interceptor.Interceptor; 

public class MyInterceptor implements Interceptor{ 

    @Override 
    public void destroy() { 
     //nothing to do 
    } 

    @Override 
    public void init() { 
     //nothing to do 
    } 

    @Override 
    public String intercept(ActionInvocation invocation) throws Exception { 
     System.out.println("Something to do before the action!"); 
     String resultString = invocation.invoke(); 
     System.out.println("Something to do after the action!"); 
     return resultString; 
     //if you are not doing post processing it is easiest to write 
     //return invocation.invoke(); 
    } 
} 
+0

雅,謝謝,我明白,當我。如果(result.equalsIgnoreCase( 「成功」)) \t \t \t \t { \t \t \t的System.out.println( 「行動後」)再次加入這一行,並感謝; \t \t \t \t} – Pawan 2012-03-31 18:47:11

相關問題