首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Struts 1.x 常見異常診斷手冊:11 大錯誤代碼與解決方案

     編輯:Java 相關知識

前言

Struts 1.x 透過 `struts-config.xml`、`ApplicationResources.properties` 等配置驅動,大多數異常源於配置與代碼不一致。本文整理 11 大高頻異常,附帶定位技巧。

異常清單與解決方案

1. "No bean found under attribute key XXX"

原因:`struts-config.xml` 定義 `` 的 `type` 類不存在、拼寫錯誤,或 `` 引用不存在的 form-bean。

解決:檢查類全名、套件路徑、JAR 是否在 `WEB-INF/lib`。

2. "Cannot find bean XXX in any scope"

原因:JSP `` 或 `request.getAttribute("xxx")` 取不到物件。

排查:

  • Action 是否 `request.setAttribute("xxx", obj)` 並正確 forward
  • Scope 是否匹配 (request/session/application)
  • `` 內部 `` 的 `id`/`name` 一致性

3. "Missing message for key "XXX""

原因:`` 在 `ApplicationResources.properties` 找不到鍵值。

解決:

  • 確認 properties 檔編碼 (ISO-8859-1 需 `native2ascii` 轉義)
  • 多模組專案:`` 的 `message-resources` 參數指定正確檔名

4. "No getter method for property XXX of bean YYY"

原因:JSP `` 對應的 `getWrongProp()` 不存在。

解決:檢查拼寫 (如 `cade` → `code`)、Getter 命名規範、Boolean 型是否用 `isXxx()`。

5. "Cannot find ActionMappings or ActionFormBeans collection"

原因:`ActionServlet` 初始化失敗,導致配置集合未載入。常見於 `struts-config.xml` 遺失或解析錯誤。

6. "Cannot retrieve mapping for action /XXX"

原因:JSP `

` 對應的 `` 未在 `struts-config.xml` 定義。

7. HTTP Status 404 - /xxx/xxx.jsp

原因:`` 路徑錯誤。

規則:

  • 同模組 forward:`path` **不含** 模組前綴
  • 跨模組 forward:加 `contextRelative="true"` + 完整路徑

8. 空白頁面、無異常、無日誌

原因:Action 返回的 `ActionForward` 名稱與 `struts-config.xml` `` 不匹配,導致 `RequestDispatcher` 找不到目標。

9. "The element type "XXX" must be terminated by the matching end-tag "XXX""

原因:`struts-config.xml` XML 格式錯誤 (標籤未閉合、特殊字元未轉義)。

工具:IDE XML 驗證、`xmllint --valid struts-config.xml`。

10. "Servlet.init() for servlet action threw exception" + NPE at ActionServlet.parseModuleConfigFile:1003

真實案例:CVS 同步時誤刪 `struts-config.xml`,導致 `InputStream` 為 null 拋 NPE。

診斷技巧:下載 Struts 原始碼,對 `ActionServlet.java` 關鍵行打斷點,觀察變數狀態。

11. "Resources not defined for Validator"

原因:`validation.xml` 定義的 `` 對應的資源鍵在 properties 檔缺失,或 form 名稱與 ActionForm `name` 不符。

通用診斷流程

  1. 閱讀完整堆疊追蹤,定位「第一行使用者代碼」
  2. 檢查 `struts-config.xml`、`validation.xml`、properties 三大配置一致性
  3. 啟用 Struts 除錯日誌:`log4j.logger.org.apache.struts=DEBUG`
  4. 瀏覽器 Network 面板確認請求 URL、參數、轉向鏈
  5. 單元測試 Action `execute()` 方法隔離驗證邏輯

遷移建議

Struts 1.x 已停止維護 (EOL 2013),新專案請直接使用 Spring MVC / Spring Boot,現有系統規劃逐步遷移:

  • 引入 `Spring` 管理 Service/DAO,Action 委派給 Service
  • 以 `DelegatingActionProxy` 整合 Spring Bean
  • 逐步將 JSP 改為 Thymeleaf/FreeMarker + REST Controller
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved