2013-05-10 59 views
5

我正在使用Struts 2.使用攔截器,我在每個頁面執行開始時創建一個數據庫連接。在頁面執行後運行的Struts 2攔截器?

例如,如果用戶轉到「myAction.do」,它將創建數據庫連接,然後調用myAction.do方法。

我正在尋找的是一個攔截器或其他任何方式來自動調用頁面執行後的方法,這將關閉數據庫連接。

這可能嗎?

回答

4

在攔截器中,您可以編寫預處理和後處理邏輯。

預處理邏輯將在執行動作之前執行,並且在執行動作之後執行後處理邏輯。

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

不管你會invocation.invoke();會後執行動作

SEE HERE FOR EXAMPLE

+0

據我所知,'攔截()'被稱爲預處理後,但什麼方法被稱爲後處理?對於每個請求,「destroy()」總是被稱爲後處理,或者只是偶爾一次? – 2013-05-10 05:02:29

+0

看到我更新了我的答案 – PSR 2013-05-10 05:03:49

+0

太棒了,非常感謝。我會盡快接受你的回答。還有一個問題,如果我想運行一個自定義的動作方法,例如,如果我想在'invocation.invoke()'之前運行'myAction.setSomeValue()',你知道怎麼做? – 2013-05-10 05:08:19

1

http://blog.agilelogicsolutions.com/2011/05/struts-2-interceptors-before-between.html充分說明執行後寫

你可以有攔截器:

  1. 行動
  2. 之前
  3. 行動之間和結果
  4. 視圖中呈現

經過此處的相關網站中提到的代碼示例

攔截

之前
public class BeforeInterceptor extends AbstractInterceptor { 
    @Override 
    public String intercept(ActionInvocation invocation) throws Exception { 
     // do something before invoke 
     doSomeLogic(); 
     // invocation continue  
     return invocation.invoke(); 
    } 
    } 
} 

行動和結果之間

public class BetweenActionAndResultInterceptor extends AbstractInterceptor { 
    @Override 
    public String intercept(ActionInvocation invocation) throws Exception { 
     // Register a PreResultListener and implement the beforeReslut method 
     invocation.addPreResultListener(new PreResultListener() { 
     @Override 
     public void beforeResult(ActionInvocation invocation, String resultCode) { 
      Object o = invocation.getAction(); 
      try{ 
      if(o instanceof MyAction){ 
       ((MyAction) o).someLogicAfterActionBeforeView(); 
      } 
      //or someLogicBeforeView() 
      }catch(Exception e){ 
      invocation.setResultCode("error"); 
      } 
     } 
     }); 

     // Invocation Continue 
     return invocation.invoke(); 
    } 
    } 
} 

視圖中呈現

public class AfterViewRenderedInterceptor extends AbstractInterceptor { 
    @Override 
    public String intercept(ActionInvocation invocation) throws Exception { 
     // do something before invoke 
     try{ 
     // invocation continue  
     return invocation.invoke(); 
     }catch(Exception e){ 
     // You cannot change the result code here though, such as: 
     // return "error"; 
     // This line will not work because view is already generated 
     doSomeLogicAfterView(); 
     } 
    } 
    } 
}