本文以一個最小化的 HelloApp 為例,完整展示 web.xml 與 struts-config.xml 的標準配置,並逐項解析關鍵元素含義,適合初學者快速掌握 Struts 1.x 應用骨架。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"https://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
<display-name>HelloApp Struts Application</display-name>
<!-- ActionServlet 核心控制器 -->
<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>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>hello.jsp</welcome-file>
</welcome-file-list>
<!-- Struts 標籤庫聲明 -->
<taglib>
<taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-html.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
</taglib>
</web-app>
config 參數指定 Struts 核心配置文件路徑;load-on-startup 確保啟動時初始化;<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
"https://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<struts-config>
<form-beans>
<form-bean name="HelloForm" type="hello.HelloForm"/>
</form-beans>
<action-mappings>
<action path="/HelloWorld"
type="hello.HelloAction"
name="HelloForm"
scope="request"
validate="true"
input="/hello.jsp">
<forward name="SayHello" path="/hello.jsp"/>
</action>
</action-mappings>
<message-resources parameter="hello.application"/>
</struts-config>
| 元素/屬性 | 說明 |
|---|---|
| <form-bean> | 定義 ActionForm Bean,name 為邏輯名,type 為全限定類名 |
| <action> path | 請求路徑,對應 URL 中 *.do 前綴部分 |
| type | Action 實作類全限定名 |
| name | 關聯的 Form Bean 名稱 |
| scope | Form Bean 作用域:request 或 session |
| validate | true 觸發 validate(),失敗則轉向 input 指定頁面 |
| <forward> | 邏輯視圖名稱與實際 JSP 路徑映射,供 mapping.findForward() 使用 |
| <message-resources> | 國際化資源包,parameter 對應 WEB-INF/classes/hello/application.properties |
hello.jsp(歡迎頁);/HelloWorld.do;HelloForm,驗證通過後實例化 HelloAction;HelloAction.execute() 處理業務,返回 mapping.findForward("SayHello");hello.jsp 顯示結果。掌握這兩個配置文件,即掌握了 Struts 1.x 應用的骨架與血脈。