structs2拦截器详解
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                structs2拦截器详解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                
| Struts2(XWork)提供的攔截器的功能說明: 
 | 
很多Action共享關聯.一些Action需要輸入驗證.另一個Action可能需要一個預處理的文件上傳.另一個Action可能需要保護來自一個double的提交.一些Action需要從列表中去除和頁面駐留在頁面顯示前.
Struts Action框架使得很容易解分開決這些問使用“Interceptor”策略.當你請求一個資源,它映射到一個”action”,框架調用Action對象.但是在Action執行前,調用可以被攔截通過另一個對象.在Action執行后,調用可以再次的被攔截.我們稱這些對象為”Interceptors”(攔截器)
Understanding Interceptors(理解攔截器)
攔截器可以執行代碼在Action執行前后.很多框架核心功能是實現攔截.此特征有點像重復提交的保護,類型轉換,對象駐留,驗證,文件上傳,頁在預處理,和更多.所有的準備都是在攔截器的幫助下完成.每個攔截器就像是一個插件,所以你可以決定精確的特性,那個Action需要被支持.
攔截器可以被配置基于獨立的Action.你可以自定義攔截器混合和匹配攔截器同框架綁定.攔截器”set the stage(設置階段)”為Action類.做很多重量級事情在Action執行前.
Action的生命周期
在一些情況下,一個攔截器將保持Action被激活,因為一個重復提交或驗證失敗.攔截器也可以改變Action執行前的狀態.
攔截器定義在一個棧中指定執行的順序.在一些情況下,攔截器在棧中的順序是非常重要的.
Configuring Interceptors(配置攔截器)
Struts.xml
<package name="default" extends="struts-default">
<interceptors>
<interceptor name="timer" class=".."/>
<interceptor name="logger" class=".."/>
</interceptors>
<action name="login"
class="tutorial.Login">
<interceptor-ref name="timer"/>
<interceptor-ref name="logger"/>
<result name="input">login.jsp</result>
<result name="success"
type="redirect-action">/secure/home</result>
</action>
</package>
查看struts-default.xml,我們可以看它是如何做的.
The Default Configuration(默認的配置)
struts-default.xml (struts2-core-2.X.X.jar根目錄)
因為struts-default.xml包含了應用程序的默認配置,所有的預先定義攔截器和棧可用”out of the box”.
Framework Interceptors(框架的攔截器)
攔截器類也是使用鍵值對定義在指定的Struts配置文件中.名字指定在struts-default.xml文件中.如果你繼承了struts-defaut包,這樣你可以使用名字了.否則,他們必需定義在你的包中使用name-class對指定在<interceptors>標簽. 一個抽像的攔截器被應用,選擇相應included/exclude方法列表.
指下如下參數:
.execludeMethods-方法名被排除
.includeMethods-方法名被包含
注意:如果方法名可用在IncludeMethods和excludeMethods,它將被考慮為一個included方法.總之,includeMethods優于excludeMethods.
擴展攔截器的這個能力將是:
* TokenInterceptor
* TokenSessionStoreInterceptor
* DefaultWorkflowInterceptor
* ValidationInterceptor
Interceptor Parameter Overriding(攔截器參數覆蓋)
攔截器的參數可以被覆蓋通過下面的方式:
方法1:
<action name="myAction" class="myActionClass">
<interceptor-ref name="exception"/>
<interceptor-ref name="alias"/>
<interceptor-ref name="params"/>
<interceptor-ref name="servlet-config"/>
<interceptor-ref name="prepare"/>
<interceptor-ref name="i18n"/>
<interceptor-ref name="chain"/>
<interceptor-ref name="model-driven"/>
<interceptor-ref name="fileUpload"/>
<interceptor-ref name="static-params"/>
<interceptor-ref name="params"/>
<interceptor-ref name="conversionError"/>
<interceptor-ref name="validation">
<param name="excludeMethods">myValidationExcudeMethod</param>
</interceptor-ref>
<interceptor-ref name="workflow">
<param name="excludeMethods">myWorkflowExcludeMethod</param>
</interceptor-ref>
</action>
方法2:
<action name="myAction" class="myActionClass">
<interceptor-ref name="defaultStack">
<param name="validation.excludeMethods">myValidationExcludeMethod</param>
<param name="workflow.excludeMethods">myWorkflowExcludeMethod</param>
</interceptor-ref>
</action>
在第一種方法,整個默認棧被拷貝并且參數相應的改變.
在第二種方法,引用一個已存在的攔截器棧,就是例子中的default-stack,覆蓋驗證器和工作流攔截器excludeMethods典型應用列子.注意在標簽中,name屬性包含一個點(.),點前面的詞指定攔截器名被覆蓋和點后面的詞指定參數本身.如下所示:
<interceptor-name>.<parameter-name>
注意:同樣是這種情況name屬性用來指示攔截器棧,如果它引用攔截本身將會使用方法1所描述的.
Order of Interceptor Execution(攔截器執行順序)
攔截器提供了一個非常好的包裝在處理的前后.這個概念減少了重復代碼.
<interceptor-stack name="xaStack">
<interceptor-ref name="thisWillRunFirstInterceptor"/>
<interceptor-ref name="thisWillRunNextInterceptor"/>
<interceptor-ref name="followedByThisInterceptor"/>
<interceptor-ref name="thisWillRunLastInterceptor"/>
</interceptor-stack>
注意:相同的攔截器將會中斷statck/chain/flow …所以順序是非常重要的.
攔截器實現com.opensymphony.xwork.interceptor.PreResultListener將會運行在Action execute之后但是在Result執行之前.
thisWillRunFirstInterceptor
thisWillRunNextInterceptor
followedByThisInterceptor
thisWillRunLastInterceptor
MyAction1
MyAction2 (chain)
MyPreResultListener
MyResult (result)
thisWillRunLastInterceptor
followedByThisInterceptor
thisWillRunNextInterceptor
thisWillRunFirstInterceptor Alias Interceptor(別名攔截器)
這個攔截器的目標是為name參數取一個別名到不同的name參數.充當膠水來連接Action共享相同的參數(但是不同名字),它連接成鏈非常有幫助.
Action的別名表達式應訪是#{"name1" : "alias1", "name2" : "alias2" }的形式.這意味著,假定一個Action(或一些其它在棧中)有一個表達式名字name1值和這個Action的攔截器應用到一個setter名字是alias1,alias1將被設置值從name1.
參數: aliasesKey(可選)-Action的名字參數查找別名映射(默認是aliases).
Extending the Interceptor(擴展攔截器)
這個攔截器沒有任何的擴展點.
例子
<action name="someAction" class="com.examples.SomeAction">
<!-- The value for the foo parameter will be applied as if it were named bar -->
<param name="aliases">#{ 'foo' : 'bar' }</param>
<interceptor-ref name="alias"/>
<interceptor-ref name="basicStack"/>
<result name="success">good_result.ftl</result>
</action>
Chaining Interceptor(鏈攔截器)
攔截器拷貝值棧中每個對象的所有屬性到當前執行對象,除非對像實現Unchainable.一收集選項includes 和 excludes可能提供控制和那一個參數將會被拷貝.僅includes或execludes可以被指定.指定兩者未定義的行為.見Java文檔{@link OgnlUtil#copy(Object, Object, java.util.Map, java.util.Collection, java.util.Collection)}獲取更多的信息.
記著如果實際上沒有對象在棧中,這個攔截器什么也不做是很重要的.這意味著兩件事情:一是,你可以安全的應用它到你的所有Action不用擔心任何不利的影響.二是,在你的Action調用之前確保棧中存在一個對象.常見的方法是通過使用chain結果類型,他組個這個攔截器來確保Action鏈特性.
參數:
.excludes(可選)-名字列表將會從拷貝中排除(所有的其它將會被包含).
.includes(可選)-名字列表將會被拷貝(所有的其它將會被排除).
Extending the Interceptor(擴展攔截器)
該攔截器沒有擴展點。
<action name="someAction" class="com.examples.SomeAction">
<interceptor-ref name="basicStack"/>
<result name="success" type="chain">otherAction</result>
</action>
<action name="otherAction" class="com.examples.OtherAction">
<interceptor-ref name="chain"/>
<interceptor-ref name="basicStack"/>
<result name="success">good_result.ftl</result>
</action>
Checkbox Interceptor(checkbox攔截器)
查找隱藏標識字段指定checkbox的最初值.如果checkbox不提交,插入到參數如果它的值為’false’.
參數:
. setUncheckedValue-默認的沒檢查可以被覆蓋通過設置’uncheckedValue’屬性
擴展攔截器 無 Conversion Error Interceptor(轉換錯誤攔截器)
最好查找interceptor子類的JavaDocs,這個攔截器的完整文檔, ConversionErrorInterceptor:
這個攔截器添加的任何錯誤可以在ActionContext的轉換錯誤中找到映射為一個字段錯誤(Action實現ValidationAware來提供的).另外,一些字段驗證錯誤原始值被保存,這樣隨后的請求值返回原始值勝于Action中的值.
這其實是很重要的,因為,如果提交”abc”不能夠轉換成一個int,我們再次顯示原始字符串(“abc”)勝于顯示int類型值(像0,在很少的聲景中用戶使用).
…JavaDocs中攔截器本射, StrutsConversionErrorInterceptor:
這個攔截器繼承了ConversionErrorInterceptor但是僅添加ActionContext中Action的字段錯誤轉換,如果字段值不是null,””,或者{“”}(長度為1的字符串數組和一個空字符串).見ConversionErrorInterceptor獲取更多信息,同類型轉換文檔.
參數 .None
擴展攔截器
這個攔截器沒有擴展點.
例子
<action name="someAction" class="com.examples.SomeAction">
<interceptor-ref name="params"/>
<interceptor-ref name="conversionError"/>
<result name="success">good_result.ftl</result>
</action> Create Session Interceptor(創建會話攔截器)
這個攔截器創建HttpSession.
這個特別有用當你使用<@s.token>標簽在freemarker模板中.使用這個標簽要求HttpSession已經被創建,因為freemarker立即提交響應用客戶端.
參數 .None
擴展攔截器 .None
例子
<action name="someAction" class="com.examples.SomeAction">
<interceptor-ref name="create-session"/>
<interceptor-ref name="defaultStack"/>
<result name="input">input_with_token_tag.ftl</result>
</action> DebuggingInterceptor(調試攔截器)
提供不同的調試視圖,提供檢查頁面后臺數據的能力.
這個攔截器僅在struts.properties文件中devMode被開啟時激活.’debug’參數從參數列表中移除在Action執行前.所有的操作發生在原始結果前有機會執行.
參數
.xml-返回參數,上下文,會話和值棧以XML文檔的形式.
.console-顯示一個彈出的’OGNL控制臺’允許用戶測試OGNL表式在值棧中.XML數據從’xml’模式被插入到頁的頂部.
.command=測試OGNL表達式并且返回字符串結果.僅用于OGNL控制臺.
例子
http://localhost:8080/Welcome.action?debug=xml
Execute and Wait Interceptor(執行和等待攔截器)
ExecuteAndWaitInterceptor對長期的后臺運作非常好當展示給用戶一人進度時.這也會阻止HTTP請求超時當Action超進5或10分鐘.
使用這個攔截器是一個非常漂亮的forward.假定你的程序中包括了struts-default.xml,這個攔截器已經配置了,但是不是默認棧的一部分.因為攔截器的本質是它必需最后攔截在在棧中.
這個攔截器工作在獨立會話基礎上.這意味著同名的Action(myLongRunningAction,在上面的例子中)不能被運行多于一次在一個給定的Session中.在初始請求或任何后面的請求(在Action完成前),wait結果將被返回.wait結果負責分發后面的請求到Action,給出一個自我更新的進度.
如果沒有”wait”結果被找到,Struts將靈活的自動生成wait結果.這個結果寫在FreeMarker和在沒有Freemarker安裝的情況下不能夠運行.如果你不想部署FreeMarker,你必需提供你自己的wait結果.這是一個好事情不管怎么做,當缺省的等待頁非常的清晰.
每當wait結果被返回,Action運行在后臺時將被放置到棧的頂部.這允許你程度數據,像一個數量,在等待頁中.使用wait頁面自動重裝載請求到Action(它將通過攔截器被繞過).你可以給出一個進度.
這個攔截器也支持使用一個初始等待的延遲.在wait頁面返回給用戶前,一個初始化延遲是讓服務器等待數毫秒的時間.在等待期間,這個攔截器將會隔100毫秒被喚醒一次檢查后臺進程是否提前完成,因些,如果一項工作要花費很長時間等待頁不會顯示給用戶.
這是一個有用的例子查找Action有很長的執行時間.使用一個2000秒的延遲時間來阻止用戶的快速查詢結果并且顯示一個等待頁面.
重點:因為Action將會運行在分開的線程中,你不能夠使用ActionContext因為它是一個ThreadLocal.這意味著你需要訪問,例如,會話數據,你需要實SessionAware勝于調用ActionContext.getSession().
以actionNameBrackgroundProcess形式命名的線程將會被攔截器踢下線.例如,查詢Action將會運行作為一個線程名字為searchBackgroundProcess.
參數
. threadPriority(可選)-優先分配線程.默認是Thread.NORM_PRIORITY.
.delay(可選)- 一個初始化延遲數毫秒的等待在等待頁面顯示前(返回wait作為一個resut代碼).默認無初始化延遲.
.delaySleepInterval(可選)-僅用于延遲.用來喚醒固定的間隔延遲檢查是否后臺處理完成。默認是100毫秒.
擴展攔截器
如果你想指定準備前和/或準備后調用后臺進程.你可以繼承BackgroundProcess類和實現beforeInvocation()和afterInvoction()方法.后臺處理執行成功時,會非常有用來獲取和釋放資源.使用后臺處理擴展,繼承ExecuteAndWaitInterceptor和實現getNewBackgroundProcess()方法.
例子
<action name="someAction" class="com.examples.SomeAction">
<interceptor-ref name="completeStack"/>
<interceptor-ref name="execAndWait"/>
<result name="wait">longRunningAction-wait.jsp</result>
<result name="success">longRunningAction-success.jsp</result>
</action>
<%@ taglib prefix="s" uri="/struts" %>
<html>
<head>
<title>Please wait</title>
<meta http-equiv="refresh" content="5;url=<a:url includeParams="all" />"/>
</head>
<body>
Please wait while we process your request.
Click <a href="<a:url includeParams="all" />"></a> if this page does not reload automatically.
</body>
</html>
</pre>
<p/> <u>Example code2:</u>
This example will wait 2 second (2000 millis) before the wait page is shown to the user. Therefore
if the long process didn't last long anyway the user isn't shown a wait page.
<pre>
<action name="someAction" class="com.examples.SomeAction">
<interceptor-ref name="completeStack"/>
<interceptor-ref name="execAndWait">
<param name="delay">2000<param>
<interceptor-ref>
<result name="wait">longRunningAction-wait.jsp</result>
<result name="success">longRunningAction-success.jsp</result>
</action>
</pre>
<p/> <u>Example code3:</u>
This example will wait 1 second (1000 millis) before the wait page is shown to the user.
And at every 50 millis this interceptor will check if the background process is done, if so
it will return before the 1 second has elapsed, and the user isn't shown a wait page.
<pre>
<action name="someAction" class="com.examples.SomeAction">
<interceptor-ref name="completeStack"/>
<interceptor-ref name="execAndWait">
<param name="delay">1000<param>
<param name="delaySleepInterval">50<param>
<interceptor-ref>
<result name="wait">longRunningAction-wait.jsp</result>
<result name="success">longRunningAction-success.jsp</result>
</action>
</pre>
Exception Interceptor
攔截器組成了異常處理的核心特性.異常處理允許你映射一個異常到一個result code,像Action返回一個結果代碼代替拋出的想不到的異常.當異常發生,它包裝一個ExceptionHolder和放置到棧中.提供簡單的訪問異常從結果中.
注意:當你配置異常映射到你的配置文件.如果這個攔截器不在你的Action攔截器棧中配置將不會產生任何影響.建議你讓攔截器是棧中的第一個攔截器,確保它能完全訪問來捕獲任何異常,甚至是由其它攔截器引起的異常.
參數
.logEnabled(可選)-異常是否被記錄?(Boolean true|false)
.logLevel(可選)-什么日志級別將被使用(trace,debug,info,wrn,error,fatal)?默認為debug.
.logCategory(可選)-如果使用這個category(eg.com.mycompany.app).默認使用com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.
上面的參數被開啟我們記錄所有拋出的異常在日志文件中,和顯示一個友好的Web頁面給終端用.
擴展攔截器
如果你想要添加自定義處理為公共的異常,你可以覆蓋{@link #publishException(com.opensymphony.xwork2.ActionInvocation, ExceptionHolder)}.默認的實現放置給定的ExceptionHolder到值棧.一定制實現將被添加到日志等.
例子
<xwork>
<package name="default" extends="xwork-default">
<global-results>
<result name="success" type="freemarker">error.ftl</result>
</global-results>
<global-exception-mappings>
<exception-mapping exception="java.lang.Exception" result="error"/>
</global-exception-mappings>
<action name="test">
<interceptor-ref name="exception"/>
<interceptor-ref name="basicStack"/>
<exception-mapping exception="com.acme.CustomException" result="custom_error"/>
<result name="custom_error">custom_error.ftl</result>
<result name="success" type="freemarker">test.ftl</result>
</action>
</package>
</xwork>
File Upload Interceptor
攔截器離開MultiPartRequestWrapper,將自動應用到任何請求到它包含的文件,添加下在的參數,[File Name]是通過HTML表單給定的上傳文件名.
.[File Name]:File-實際文件
.[File Name]ContentType:String-內容類型文件
.[File Name]FileName:String-實際上傳的文件名(不是HTML的名字)
你可以獲取訪問這些文件通過Action中提供的setter,關聯到任何第三方模式上,像setDocument(File document), setDocumentContentType(String contentType),等.見例子中的代碼片斷.
這個攔截器將添加很多字段錯誤,假定Action實現ValidationAware.這些錯誤消息基于一些i18n值存儲在struts-messages.properties中,一個默認的i18n處理為所有的i18n請求.你可以覆蓋這些消息的文本通過提供的key對應用文本.
. struts.messages.error.uploading - a general error that occurs when the file could not be uploaded
.struts.messages.error.file.too.large - occurs when the uploaded file is too large
.struts.messages.error.content.type.not.allowed - occurs when the uploaded file does not match the expected content types specified
參數
.maximumSize(可選)-最大值(字節為單位)攔截器將允許一個文件引用設置到Action中,注意,這不會關聯struts.properties中的常量屬性.默認大約為2MB.
.allowedType(可選)-一個用逗號分隔的內容類型列表(例如:text/html),攔截器將允許一個文件引用設置到Action,如果指定為none允許所有類型的上傳. 擴展攔截器
你可以擴展這個攔截器和覆蓋#acceptFile方法提供更多控制,支持的文件和不支持的文件.
例子
<action name="doUpload" class="com.examples.UploadAction">
<interceptor-ref name="fileUpload"/>
<interceptor-ref name="basicStack"/>
<result name="success">good_result.ftl</result>
</action>
</pre>
And then you need to set encoding <code>multipart/form-data</code> in the form where the user selects the file to upload.
<pre>
<a:form action="doUpload" method="post" enctype="multipart/form-data">
<a:file name="upload" label="File"/>
<a:submit/>
</a:form>
</pre>
And then in your action code you'll have access to the File object if you provide setters according to the
naming convention documented in the start.
<pre>
public com.examples.UploadAction implemements Action {
private File file;
private String contentType;
private String filename;
public void setUpload(File file) {
this.file = file;
}
public void setUploadContentType(String contentType) {
this.contentType = contentType;
}
public void setUploadFileName(String filename) {
this.filename = filename;
}
...
}
</pre>
設置參數的例子:
<interceptor-ref name="fileUpload">
<param name="allowedTypes">
p_w_picpath/png,p_w_picpath/gif,p_w_picpath/jpeg
</param>
</interceptor-ref> I18n Interceptor
一個攔截器處理設置指定會話中的locale為當前的Action請求.另外,這個攔截器將查找指定的HTTP請求參數和設置locale使用提供的任何值.這意味著攔截器可以讓你的應用程序動態的改變locale為用戶的會話.這非常有用對應用程序想要支持多種語言和用戶設置他或她的語言.locale參數被移除在攔截器執行期間,確保屬性不被設置在Action上(像request_locale),不是特有的setter在Action中.
例如,使用默認的參數名,一個請示到foo.action?request_locale=en_US,locale美式英語被保存到用戶的會話中并且將用于所有的后面請求中.
參數
.parameterName(可選)-HTTP請求的參數名,locale作為開關和保存會話中,默認為request_locale
.attributeName(可選)-session key的名字存儲選中的locale.默認是WW_TRANS_I18N_LOCALE
擴展攔截器
這個攔截器沒有擴展點
例子
<action name="someAction" class="com.examples.SomeAction">
<interceptor-ref name="i18n"/>
<interceptor-ref name="basicStack"/>
<result name="success">good_result.ftl</result>
</action>
Logger Interceptor
攔截器日志開始和結束Action的執行(僅英文,非國際化).
參數 這個攔截器沒有參數.
擴展攔截器 沒有明顯的擴展到存在的攔截器.
例子
<!-- prints out a message before and after the immediate action execution -->
<action name="someAction" class="com.examples.SomeAction">
<interceptor-ref name="completeStack"/>
<interceptor-ref name="logger"/>
<result name="success">good_result.ftl</result>
</action>
<!-- prints out a message before any more interceptors continue and after they have finished -->
<action name="someAction" class="com.examples.SomeAction">
<interceptor-ref name="logger"/>
<interceptor-ref name="completeStack"/>
<result name="success">good_result.ftl</result>
</action>
Message Store Interceptor
一個攔截器存儲ValidationAware Action的消息/錯誤和字段錯誤到Http Session,這樣它將被重新獲取在最后階段.這允許Action的消息/錯誤和字段錯誤長期有效在特定的http請求.
在’STORE’模式中,攔截器將重新獲取存儲的Action 消息/錯誤和字段錯誤并且放他們到ValidationAware Action.
攔截器在’NONE’模式中什么也不做,其中一個是默認的.
操作模式可以被交換使用:
1]設置攔截器參數例子.
<action name="submitApplication" ...>
<interceptor-ref name="store">
<param name="operationMode">STORE</param>
</interceptor-ref>
<interceptor-ref name="defaultStack" />
....
</action>
2]通過請求參數(allowRequestParameterSwitch 必需為’true’,是默認的)
// the request will have the operation mode in 'STORE'
http://localhost:8080/context/submitApplication.action?operationMode=STORE
參數
. allowRequestParameterSwitch-開啟請求參數可以交換攔截器的操作模式.
. requestParameterSwitch-指示攔截器中使用什么樣的請求參數.
.operationMode-這個攔截器使用的操作模式(‘STORE’,’RETRIEVE’或’NONE’其中一個).’NONE’為默認.
擴展攔截器
下面的方法將被覆蓋:
. getRequestOperationMode-獲取攔截器的操作模式基于請求參數.
.mergeCollection-合并兩個集合.
.mergeMap – 合并兩個map
例子
<action name="submitApplication" ....>
<interceptor-ref name="store">
<param name="operationMode">STORE</param>
</interceptor-ref>
<interceptor-ref name="defaultStack" />
<result name="input" type="redirect">applicationFailed.action</result>
<result type="dispatcher">applicationSuccess.jsp</result>
</action>
<action name="applicationFailed" ....>
<interceptor-ref name="store">
<param name="operationMode">RETRIEVE</param>
</interceptor-ref>
<result>applicationFailed.jsp</result>
</action> 同上面的例子, 'submitApplication.action'有Action消息/錯誤/字段錯誤存儲到Http會話中.以后需要的時候,在這種情況下,’applicationFailed.action’被激活,它將獲取Action 消息/錯誤/字段錯誤存儲在HTTP會話中并且放回到Action. Model Driven Interceptor
查看ModelDriven Action和添加Action的模型到值棧.
注意: ModelDrivenInterceptor必需出現在StaticParametersInterceptor和ParametersInterceptor之前,如果你想要參數被應用到模型.
注意: ModelDrivenInterceptor將僅放模型到棧當模型不為null,其它的的將被忽略.
參數 None
擴展攔截器 這個攔截器沒有擴展點.
例子
<action name="someAction" class="com.examples.SomeAction">
<interceptor-ref name="model-driven"/>
<interceptor-ref name="basicStack"/>
<result name="success">good_result.ftl</result>
</action>
Scoped Model Driven Interceptor
一個開授權給范圍模型驅動的Action的攔截器.
這個攔截器僅激活實現ScopeModelDriven接口的Action.如果被檢查到.,它將重新獲取模型類從配置范圍內,這樣提共它到Action.
參數
.calssName-模型類的名字.默認為通過getModel()方法返回的對象的類名.
.name-關鍵字用來使用當存儲或重獲實例在一個范圍內。默認為模型類名.
.scope-存儲或重獲模型的范圍.默認為’request’也可以是’session’.
擴展攔截器 此攔截器無擴展點
例子
<-- Basic usage -->
<interceptor name="scoped-model-driven" class="com.opensymphony.interceptor.ScopedModelDrivenInterceptor" />
<-- Using all available parameters -->
<interceptor name="gangsterForm" class="com.opensymphony.interceptor.ScopedModelDrivenInterceptor">
<param name="scope">session</param>
<param name="name">gangsterForm</param>
<param name="className">com.opensymphony.example.GangsterForm</param>
</interceptor>
Servlet Config Interceptor
一個攔截器設置Action屬性基于接口實現的Action。例如,如果Action實現ParameterAware那么Action上下文的參數映射將會被設置.
這個攔截器設計來設置一有的屬性,一個Action需要知道Servlet參數,servlet上下文,會話等等.接口支持:
ServletContextAware
ServletRequestAware
ServletResponseAware
ParameterAware
RequestAware
SessionAware
ApplicationAware
PrincipalAware
參數 無
擴展攔截器 此攔截器無擴展點。
例子
<action name="someAction" class="com.examples.SomeAction">
<interceptor-ref name="servlet-config"/>
<interceptor-ref name="basicStack"/>
<result name="success">good_result.ftl</result>
</action>
Static Parameters Interceptor
這個攔截器位于靜態參數定義的Action配置文件中.如果Action實現Parameterizable,靜態參數映射的Map將會被直接傳遞到Action.
參數典型的定義在<param>元素內存在于xwork.xml文件中.
參數 None
擴展攔截器 這個攔截器沒有擴展點.
例子
<action name="someAction" class="com.examples.SomeAction">
<interceptor-ref name="static-params">
<param name="parse">true</param>
</interceptor-ref>
<result name="success">good_result.ftl</result>
</action> Roles Interceptor
它被執行僅當用戶有正確的角色. Timer Interceptor
這個攔截器記錄時間單位為毫秒.為了使這個攔截器正常的工作,日志框架必需被設置,至少是INFO級別.這個攔截器依賴于Commons Logging API 報告執行時間值.
參數
.logLevel(可選的)-我們使用什么日志級別(trace,debug,info,warn,error,fatal)? –默認為info
.logCategory(可選的)-假如我們使用這個類別(eg.com.mycompany.app).默認使用com.opensymphony.xwork2.interceptor.TimerInterceptor.
開啟上面的參數我們記錄所有的Action執行期間的日志到日志文件中.
擴展攔截器
這個攔截器可以被擴展提供定制的消息格式.用戶可以覆蓋invokeUnderTiming方法.
例子
<!-- records only the action's execution time -->
<action name="someAction" class="com.examples.SomeAction">
<interceptor-ref name="completeStack"/>
<interceptor-ref name="timer"/>
<result name="success">good_result.ftl</result>
</action>
<!-- records action's execution time as well as other interceptors-->
<action name="someAction" class="com.examples.SomeAction">
<interceptor-ref name="timer"/>
<interceptor-ref name="completeStack"/>
<result name="success">good_result.ftl</result>
</action> Token Interceptor
確保僅有一個請求每個標記被處理.這個攔截器可以確保回退按鈕和雙擊不會引起非預想到的影響.例如,你可以使用它來阻止粗心的用戶雙擊一個”check out”按鈕在一個在線商店中.這個攔截器使用一個完全原始的支術當一個無效的標記被找到;它將返回結果invalid.token,它可以被映射到你的Action配置中.一個更復雜的實現, TokenSessionStoreInterceptor,可以提供更好的邏輯當無效的標記被找到.
注意:設置一個token在你的表單中,你必需使用token標簽.這個標簽要求并且必需用于表單中,提交到Action保護通過這個攔截器.一些請求不提供token(使用token標簽)將會被處理做為一個無效的token請求.
國際化注意事項:下面的key可以用于國際化Action錯誤生成通過這個token攔截器.
. struts.messages.invalid.token
注意:當這個方法離開MethodFilterInterceptor擴展時,它有能力決定選擇Action中的方法,見MethodFilterInterceptor獲取更多的信息.
參數 None
擴展攔截器
用戶不經常擴展它,這個攔截器擴展通過TokenSessionStoreInterceptor. handleInvalidToken和handleValidToken方法保護和可用更多有趣的邏輯,像做token會話攔截.
例子
<action name="someAction" class="com.examples.SomeAction">
<interceptor-ref name="token"/>
<interceptor-ref name="basicStack"/>
<result name="success">good_result.ftl</result>
</action>
<-- In this case, myMethod of the action class will not
get checked for invalidity of token -->
<action name="someAction" class="com.examples.SomeAction">
<interceptor-ref name="token">
<param name="excludeMethods">myMethod</param>
</interceptor-ref name="token"/>
<interceptor-ref name="basicStack"/>
<result name="success">good_result.ftl</result>
</action> Token Session Interceptor
攔截器不是從TokenInterceptor構建,提供先進的邏輯處理無效的token.不像普通token攔截器,這個攔截器將嘗試提供智能的失敗處理在多個請求事件請求使用相同的會話.那樣,它將阻礙后面的請求,直到前一個請求完成,并且代替換返回invalid.token代碼,它將嘗試顯示相同的原始資源,如果沒有多個請求被提交在第一個地方,驗證Action調用將會顯示.
注意:像遠離MethodFilterInterceptor方法,它能決定是僅選擇適當的方法在Action類中,見來MethodFilterInterceptor獲取更多的信息.
參數 None
擴展攔截器 這個攔截器沒有擴展點.
例子
<action name="someAction" class="com.examples.SomeAction">
<interceptor-ref name="token-session/>
<interceptor-ref name="basicStack"/>
<result name="success">good_result.ftl</result>
</action>
<-- In this case, myMethod of the action class will not
get checked for invalidity of token -->
<action name="someAction" class="com.examples.SomeAction">
<interceptor-ref name="token-session>
<param name="excludeMethods">myMethod</param>
</interceptor-ref name="token-session>
<interceptor-ref name="basicStack"/>
<result name="success">good_result.ftl</result>
</action> Validation Interceptor
這個攔截器運行Action通過標準的驗證框架,輪流檢查針對其它的驗證規則(查找文件像ActionClass-validation.xml)和添加字段級和Action級錯誤消息(提供通過Action實現com.opensymphony.xwork2.ValidationAware),這個攔截器通常是最后一個(或僅次于最后一個)應用到棧中的攔截器,同樣的假定所有的值已經被設置到Action.
如果方法名被調用指定在excludeMethods參數,攔截器什么也不做.excludeMethods接收一個逗號分隔的方法名列表.例如,請求foo!input.action和foo!back.action將會被跳過通過這個攔截器,如果你設置excludeMethods參數到”input,back”.
注意什么也不用做使用com.opensymphony.xwork2.Validateable接口并且簡單的添加錯誤消息到Action.Action請求的流程不會改變原有的攔截器.寧原這個攔截器常常在conjuction同workflow攔截器使用.
注意:因為這個方法不是從MethodFilterInterceptor繼承, 它能決定是僅選擇適當的方法在Action類中,見來MethodFilterInterceptor獲取更多的信息.
參數 None
擴展攔截器 這個攔截器無擴展點
例子
<action name="someAction" class="com.examples.SomeAction">
<interceptor-ref name="params"/>
<interceptor-ref name="validation"/>
<interceptor-ref name="workflow"/>
<result name="success">good_result.ftl</result>
</action>
<-- in the following case myMethod of the action class will not
get validated -->
<action name="someAction" class="com.examples.SomeAction">
<interceptor-ref name="params"/>
<interceptor-ref name="validation">
<param name="excludeMethods">myMethod</param>
</interceptor-ref>
<interceptor-ref name="workflow"/>
<result name="success">good_result.ftl</result>
</action>
轉載于:https://blog.51cto.com/sean2012/967112
總結
以上是生活随笔為你收集整理的structs2拦截器详解的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: poj3852
- 下一篇: 俄罗斯四人***团伙黑掉整个城市ATM机
