Action配置完了就該配置返回結果了,這樣才能讓它們關聯起來哦
7.配置結果類型
Struts2使用<result/>元素在struts.xml文件中進行結果配置,根據<result/>元素的位置不同,可以分爲:
l 局部結果:將<result/>配置在<action/>中;
l 全部結果:將<result/>配置在<global-results/>中;
<result/>元素的有兩個屬性,分別是name屬性和type屬性,此外在<result/>元素中還可以配置<param/>元素,<param/>元素的name屬性可以爲location和parse這兩個值,其中location指定了邏輯視圖所對應的實際視圖資源;而parse則指定是否允許在實際視圖資源中使用OGNL表達式,parse默認值爲true。
如果在配置<result/>時沒有指定location屬性值,則<result/>自動將<result></result>之間的字符串值作爲實際視圖資源;如果沒有指定name屬性,則採用默認值success,如果沒有指定type類型,則默認爲dispatcher結果類型。
如果一個Action裏包含也全部結果同名的結果,則Action裏的局部結果將會覆蓋全局Action。
8.Struts2支持的結果類型
Struts2支持多種結果類型,除了最常用的jsp頁面外,也支持像Velocity、FreeMarker、Jasper等;Struts2的結果類型要求實現com.opensymphony.xwork.Result,Struts2在struts-default.xml中配置了一系列默認的結果類型,其中dispatcher爲默認的結果類型:
l chain:Action鏈式處理的結果類型;
l chart:整合JFreeChart的結果類型;
l dispatcher:用於JSP整合的結果類型;
l freemarker:FreeMarker整合的結果類型;
l httpheader:控制特殊的HTTP行爲的結果類型;
l jasper:JasperReports整合的結果類型;
l jsf:JSF整合的結果類型;
l redirect:直接跳轉到其它URL的結果類型;
l redirect-action:直接跳轉到其它Action的結果類型;
l stream:向瀏覽器返回一個InputStream;
l tiles:與Tiles整合的結果類型;
l velocity:與Velocity整合的結果類型;
l xslt:與XML/XSLT整合的結果類型;
l plaintext:顯示某個頁面的原始代碼的結果類型;
dispatcher結果類型與redirect結果類型的差別是轉發和重定向的差別:重定向會丟失所有的請求參數、請求屬性、Action的處理結果等,即是說redirect的效果就是重新產生一個新請求,其實系統內部是調用HttpServletResponse的sendRedirect(String)方法來重定向資源的。
當一個Action處理結束後直接將請求重定向到另一個Action時需要使用redirect-action結果類型,並提供actionName及namespace的值,其中actionName爲重定向的Action名,namespace爲重定向的Action所在的命名空間。
9.動態結果
在前面的動態方法調用中已經提及到使用表達式來動態指定<result/>元素的實際視圖資源,除了此種方法外,還可以使用${屬性名}的方式來指定視圖資源,這裏的屬性名就是對應Action實例裏的屬性,除了這種單屬性名錶達式的形式外,還可以使用完全的OGNL表達式,如${屬性名.屬性名.屬性名……},示例如下:
<action name=”demo” class=”com.demo.DemoAction” namespace=”/demo”>
<result name=”error”>/error.jsp</result>
<result name=”success” type=”redirect”>
EditAction.do?recoredId=${currentUser.userId}
</result>
</action>
上述配置中使用${currentUser.userId}表達式來指定success後的視圖資源,對於這樣的表達式,要求在對應的DemoAction中包含currentUser屬性,且currentUser屬性必須包含userId屬性,否則${currentUser.userId}的值將爲null。