您的位置:首页 > 编程语言 > Java开发

Struts Gossip: 模組化程式

2009-07-09 17:48 169 查看
來源:http://caterpillar.onlyfun.net/Gossip/Struts/ModuleUnit.htm

Struts中很多設定都是在struts-config.xml中加以設定,在大型網站的開發中,有很多小團隊會負責不同的模組,如果每一個團隊都要對struts-config.xml進行設定,將會導致struts-config.xml的版本控制問題。

在Struts 1.1中,您可以為不同的模組分配不同的struts-config.xml設定檔,方法是在ActionServlet的config參數後加上後綴字,例如將使用者登入的工作切分為login模組,則可以這麼在web.xml中設定:

web.xml

...

<servlet>

<servlet-name>action</servlet-name>

<servlet-class>

org.apache.struts.action.ActionServlet

</servlet-class>

<init-param>

<param-name>config</param-name>

<param-value>

/WEB-INF/conf/struts-config.xml

</param-value>

</init-param>

<init-param>

<param-name>config/login</param-name>

<param-value>

/WEB-INF/conf/struts-config-login.xml

</param-value>

</init-param>

<load-on-startup>2</load-on-startup>

</servlet>

...


onfig/login指定了login模組所使用的設定檔struts-config-login.xml,現在
login模組的開發人員只要專心於自己的開發與設定檔,就如同之前的主題一般的設定,當ActionServlet收到請求時,它是根據模組前綴來瞭解
該使用哪一個模組,例如:
http://localhost:8080/strutsapp/login/admin.do
像上面的URL,我們稱/strutsapp/login/admin.do是相對於domain的路徑,而/login/admin.do是相對於應用程式context的路徑,而admin.do是相對於login模組。

當ActionServlet接收請求,它判斷URL中相對於context的前綴,例如上例中的login,於是得知該使用login模組,而在每個模
組的struts-config-xxx.xml中的設定則是相對於模組路徑的,也就是說如果是struts-config-
login.xml中的這樣設定:

struts-config-login.xml

....

<action

path="/admin"

type="onlyfun.caterpillar.AdminLoginAction"

name="adminForm">

<forward

name="adminPage"

path="/WEB-INF/pages/admin/admin.jsp"/>

....


則所有的path設定會自動被加上login前綴,例如必須使用以下的路徑才可以正確的請求到AdminLoginAction:
http://localhost:8080/strutsapp/login/admin.do
在模組中的 Action
在查找forward時,都是以所在的模組查找對應的struts-config-xxx.xml,例如上例的AdminLoginAction運行中查
找forward時,則會查找struts-config-login.xml中的forward,也就是說,模組中forward對象的查找預設都是相
對於模組路徑,而不是相對於context路徑。

那麼如何從目前的模組轉換到另一個模組?

當您的應用程式分作多個模組時,在使用者點選某個鏈結時,您有兩個方法可以在模組之間切換,第一個方法是使用相對於context的路徑來進行
forward
查找,您可以在當前的模組所使用的struts-config-xxx.xml中設定,例如在struts-config-login.xml中加入:

....

<global-forwards>

<forward

name="switchModuleToSystem"

contextRelative="true"

path="/system/index.do"

redirect="true"/>

</global-forwards>

....

這是在全區可查找的forward中的設定,在<action>標籤中也可以像上面一樣使用<forward>標籤,,例如:

....

<action ... >

<forward

name="switchModuleToProfile"

contextRelative="true"

path="/profile/personalInfo.do"

redirect="true"/>

</action>

....

另一切換模組的方法就是使用SwitchAction,它需要在請求中帶兩個參數,一個是prefix,用來指定模組前綴名稱,一個是page,用來指定相對於模組的資源路徑,例如可以這麼設定:

....

<action-mappings>

<action

path="/switchModule"

type="org.apache.struts.actions.SwitchAction
"/>

</action-mappings>

....

之後可以使用這樣的路徑與參數來請求profile模組的personalInfo.do:
http://yourapp/switchModlue.do?prefix=/profile&page=/personalInfo.do
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: