一、dispatcher
(1)為預設的result類型,一般情況下我們在struts.xml會這麼寫:
<result name="success">/main.jsp</result>
以上寫法使用了兩個預設,其完整的寫法為:
# <result name="success" type="dispatcher">
# <param name="location">/maini.jsp</param>
# </result>
第一個預設:type="dispatcher";第二個預設:設定的為location參數,location隻能是頁面,不能是另一個action(可用type="chain"解決)。
(2)實作方式
從doExecute方法看出,有三個出口(finalLocation為要跳轉的位址):
pageContext.include(finalLocation);
dispatcher.forward(request, response); (dispatcher是根據finalLocation建立的)
dispatcher.include(request, response);
而我們知道,forward與include都是轉發到context内部的資源。
二、redirect
(1)可以重定向到一個頁面,另一個action或一個網址。
# <result name="success" type="redirect">aaa.jsp</result>
# <result name="success" type="redirect">bbb.action</result>
# <result name="success" type="redirect">www.baidu.com</result>
(2)實作方式:
檢視doExecute方法,隻有一個出口:
response.sendRedirect(finalLocation);
sendRedirect是重定向,是重新産生一個HTTP請求到伺服器,故重定向後其原來所在的action上下文就不可用了。
三、chain
(1)主要用于把相關的幾個action連接配接起來,共同完成一個功能。
# <action name="step1" class="test.Step1Action">
# <result name="success" type="chain">step2.action</result>
# </action>
#
# <action name="step2" class="test.Step2Action">
# <result name="success">finish.jsp</result>
# </action>
(2)實作方式:
檢視execute()方法,主要思想如下:
// 根據Action名稱finalActionName及要調用的方法finalMethodName來new一個代理對象proxy,并執行之
# proxy = actionProxyFactory.createActionProxy(finalNamespace,
# finalActionName, finalMethodName, extraContext);
# proxy.execute();
(3)多個action間資料的傳遞
主要有兩種方式:
1。由于處于chain中的action屬于同一個http請求,共享一個ActionContext,故可以在上下文中擷取,在頁面上可以直接使用。手動擷取的方法如下:
# HttpServletRequest request = ServletActionContext.getRequest();
# String s=(String)request.getAttribute("propName");
2。實作ModelDriven接口
在Step1Action中,加入getModel:
# public Object getModel() {
# return message;
# }
在Step2Action中,加入setModel:
# public void setModel(Object o){
# System.out.println("message is:"+o);
# }
注意,setModel的調用先于execute()方法後于構造方法。