web.xml 是 Java Web 應用部署描述符,Struts 應用需在其中配置核心控制器、歡迎頁面、錯誤頁面、標籤庫等關鍵項。本文詳細說明各配置元素與屬性。
<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>
<init-param>
<param-name>debug</param-name>
<param-value>2</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>2</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
常用子元素:<servlet-name>、<servlet-class>、<init-param>(配置啟動參數)。
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<servlet-name> 必須與聲明一致。常用模式 *.do、/app/*。
提示: 整個應用(含多模塊)只需配置一個 ActionServlet。Servlet 本身支援多線程,Struts 框架也限制單實例。多 ActionServlet 純屬多餘。
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.html</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
容器按順序查找,找到第一個存在的文件返回;全不存在則 404。
<error-page>
<error-code>404</error-code>
<location>/error/404.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/error/500.jsp</location>
</error-page>
<error-page>
<exception-type>java.lang.NullPointerException</exception-type>
<location>/error/nullptr.jsp</location>
</error-page>
<error-page>
<exception-type>javax.servlet.ServletException</exception-type>
<location>/error/servlet.jsp</location>
</error-page>
可捕獲:RuntimeException/Error、ServletException 及子類、IOException 及子類。
<taglib>
<taglib-uri>/tags/struts-bean</taglib-uri>
<taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/tags/struts-html</taglib-uri>
<taglib-location>/WEB-INF/struts-html.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/tags/struts-logic</taglib-uri>
<taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/tags/struts-tiles</taglib-uri>
<taglib-location>/WEB-INF/struts-tiles.tld</taglib-location>
</taglib>
<taglib-uri>:JSP 頁面 <%@ taglib uri="..." %> 引用的邏輯名。<taglib-location>:TLD 文件在 WAR 內的物理路徑。若未使用 Struts 標籤庫,可省略此配置。同理可註冊自定義標籤庫。
load-on-startup>1 確保啟動時初始化 Struts,減少首請求延遲。/error/ 目錄,統一風格、記錄日誌。/tags/struts-*),避免衝突。web.xml 重複上述配置,或使用 Struts 1.1+ 模塊機制共享單一 ActionServlet。