在Struts中,您所有關於請求轉發等的設定都是在struts-config.xml中定義,很快的,您的 struts-config.xml就會膨漲為好幾百行,甚至好幾千行。
您可以使用 模組化程式 的方式,將相關的功能設定加以分類,並撰寫在不同的struts-config-xxx.xml模組設定檔案中。
在Struts 1.2中新增了通配字元(wildcard)設定,您可以在struts-config.xml中使用通配字元,透過事前設計好的命名規範,加上通配字元設定,您可以大量的減少struts-config.xml中的設定行數。
以一個實際的例子來看,如果您本來的struts-config.xml中的設定是這樣的:
.... <action path="/editProfile" type="onlyfun.caterpillar.EditProfileAction" name="profileForm" scope="request" validate="false"> <forward name="failure" path="/mainMenu.jsp"/> <forward name="success" path="/profile.jsp"/> </action>
<action path="/editDocument" type="onlyfun.caterpillar.EditDocumentAction" name="documentForm" scope="request" validate="false"> <forward name="failure" path="/mainMenu.jsp"/> <forward name="success" path="/document.jsp"/> </action> ....
則在Struts 1.2中可以這麼撰寫就好了:
.... <action path="/edit*" type="onlyfun.caterpillar.Edit{1}Action" name="{1}Form" scope="request" validate="false"> <forward name="failure" path="/mainMenu.jsp"/> <forward name="success" path="/{1}.jsp"/> </action> ....
如上設定,如果是edit開頭的請求,就會與通配字元比對,並將除去前綴部份字串作為查找Action的依據,例如
/editProfile.do就會查找EditProfileAction的action設定,而/editDocument.do就會查找
EditDocumentAction的action設定。
通配字元*最多可以設定九個,依序對應至{1}到{9},例如/edit*Profile*.do與edit{1}Profile{2}Action的關係。
設定{0}的話,表示會包括整個請求,即包括前綴,例如/edit*.do與Admin{0}Action的關係的一個例子是,在請求為 /editProfile.do時,會呼叫AdminEditProfileAction這個action。
通配字元設定主要包括以下:
| * |
比對一個或多個字元,不包括斜線 ('/') 字元 |
| ** |
比對一個或多個字元,包括斜線 ('/') 字元 |
| \character |
反斜線字元被用於跳脫字元,所以 \* 會用於比對星號 ('*'),而
\\ 比對反斜線 ('\'). |
目前Struts 1.2中 <action-mappings> 支持通配字元設定的屬性有:
- type
- name
- roles
- parameter
- attribute
- forward
- include
- input
|