讓我們來看看如何使用一個已經存在的攔截我們的“Hello World”程序。我們將使用定時器攔截器,其目的是測量過了多長時間,執行相應的操作方法。同時我PARAMS攔截器,其目的是發送的請求參數的行動。您可以嘗試不使用這個攔截器和你的榜樣,你會發現,name屬性沒有被設置的參數是不能夠達到給動作。
我們將繼續HelloWorldAction.java,web.xml中,HelloWorld.jsp和index.jsp文件,因為他們已經創建的實例章,但讓我們如下修改struts.xml文件中添加一個攔截器
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.devMode" value="true" /> <package name="helloworld" extends="struts-default"> <action name="hello" class="com.yiibai.struts2.HelloWorldAction" method="execute"> <interceptor-ref name="params"/> <interceptor-ref name="timer" /> <result name="success">/HelloWorld.jsp</result> </action> </package> </struts>
右鍵點擊項目名稱,並單擊“導出”> WAR文件創建一個WAR文件。然后,這WAR部署在Tomcat的webapps目錄下。最后,啟動Tomcat服務器,並嘗試訪問URL http://localhost:8080/HelloWorldStruts2/index.jsp。這會給你以下畫面:
現在,在給定的文本框中輸入任何單詞,然后單擊“Say Hello按鈕執行已定義的動作。現在如果你將檢查生成的日志,你會發現下面的文字:
INFO: Server startup in 3539 ms 27/08/2011 8:40:53 PM com.opensymphony.xwork2.util.logging.commons.CommonsLogger info INFO: Executed action [//hello!execute] took 109 ms.
這里的底線是產生,因為定時器攔截行動,告訴了要執行的總109ms
創建自定義攔截器
在應用程序中使用自定義攔截器是一個優雅的方式來提供跨領域的應用功能。創建一個自定義攔截器是容易的,需要擴展的接口,下面Interceptor接口內容:
public interface Interceptor extends Serializable{ void destroy(); void init(); String intercept(ActionInvocation invocation) throws Exception; }
正如其名稱所表明的,在init()方法提供了一種方法來初始化攔截器destroy()方法提供了一個攔截器凈化設施。不同的行動,攔截器的請求重用和需要是線程安全的,特別是在intercept()方法。
ActionInvocation對象提供的運行時環境。它允許訪問的行動本身和方法調用的行動和決定的行動是否已經調用。
如果您有沒有必要的初始化或清理代碼,AbstractInterceptor類可以擴展。這提供了一個默認的無操作實現 init() 和destroy()方法。
創建攔截器類:
讓我們創建MyInterceptor.java在Java資源> src文件夾:
package com.yiibai.struts2; import java.util.*; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; public class MyInterceptor extends AbstractInterceptor { public String intercept(ActionInvocation invocation)throws Exception{ /* let us do some pre-processing */ String output = "Pre-Processing"; System.out.println(output); /* let us call action or next interceptor */ String result = invocation.invoke(); /* let us do some post-processing */ output = "Post-Processing"; System.out.println(output); return result; } }
就像你看到的,實際的動作將使用攔截器執行的invocation.invoke()調用。所以,你可以做一些前處理和后處理根據您的需要。
框架本身開始的過程,在第一次調用ActionInvocation對象的invoke()。每次invoke()被調用,ActionInvocation咨詢狀態並執行攔截。當所有配置的攔截器被調用,invoke()方法將導致要執行的動作本身。通過請求流以下數據圖顯示了相同的概念: