Struts 應用採用兩個 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/struts-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
重點:全應用僅需一個 ActionServlet(Servlet 本身多執行緒),初始化參數 config 指定 Struts 設定檔路徑。
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<error-page>
<error-code>404</error-code>
<location>/error/404.jsp</location>
</error-page>
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/error/exception.jsp</location>
</error-page>
<taglib>
<taglib-uri>/tags/struts-bean</taglib-uri>
<taglib-location>/WEB-INF/tld/struts-bean.tld</taglib-location>
</taglib>
根元素 <struts-config> 對應 ModuleConfig 類別,子元素順序嚴格遵循 DTD 定義:
data-sources? → form-beans? → global-exceptions? → global-forwards?
→ action-mappings? → controller? → message-resources? → plug-in*
| 元素 | 用途 | 關鍵屬性 |
|---|---|---|
| <data-sources> | 資料源連線池配置 | JNDI 名稱、驅動類別、URL、帳密 |
| <form-beans> | ActionForm 定義 | name(邏輯名)、type(完整類名) |
| <global-exceptions> | 全域例外處理對應 | type(例外類別)、path(轉向頁面) |
| <global-forwards> | 全域邏輯轉向 | name、path、redirect(true=重導向) |
| <action-mappings> | Action 路徑對應 | path、type、name、scope、validate、input、forwards |
| <controller> | ActionServlet 參數調整 | bufferSize、contentType、locale、tempDir、nocache |
| <message-resources> | 國際化資源檔 | parameter(資源檔基底名)、key、factory |
| <plug-in> | 擴充外掛(如 Validator、Tiles) | className、配置屬性 |
所有子模組共享單一 ActionServlet 實例,但各擁有獨立 struts-config.xml。在 web.xml 中為 ActionServlet 新增多個 init-param(參數名含模組前綴),並透過 ActionServlet 的 config/ 前綴機制切換模組。
啟動時由 Apache Digester 解析 XML,建構 org.apache.struts.config 套件下的 JavaBean 物件樹(ModuleConfig 為根),載入記憶體供執行期存取。Eclipse 等 IDE 提供視覺化編輯器,實務上僅需填寫屬性值。