在使用 Struts2 框架開發過程中,開發者經常會遇到配置檔案載入失敗、動作映射找不到等問題。本文整理了最常見的錯誤場景及快速解決方案,助你快速定位問題根因。
錯誤堆疊追蹤:
Unable to load configuration. - bean - jar:file:/path/struts2-core-x.x.x.jar!/struts-default.xml
Struts2 核心配置檔 struts-default.xml 位於 struts2-core.jar 內部。當專案啟動時,框架會自動載入此檔案以初始化預設攔截器、結果類型等核心組件。若出現載入失敗,通常是以下原因:
struts2-core.jarProject > Clean...,勾選「清理所有專案」,然後重新發布到伺服器。mvn dependency:tree 檢查是否存在多版本 Struts2 JAR,透過 <exclusion> 排除傳遞性依賴。StrutsPrepareAndExecuteFilter 過濾器配置正確,且 url-pattern 涵蓋所有需處理的請求。| 錯誤現象 | 可能原因 | 解決方向 |
|---|---|---|
| There is no Action mapped for namespace /xxx | 動作映射路徑錯誤、namespace 不匹配 | 檢查 struts.xml 中 package 的 namespace 與 action name |
| ClassNotFoundException: org.apache.struts2.dispatcher.FilterDispatcher | Struts2 版本過舊,FilterDispatcher 已棄用 | 升級至 Struts 2.5+,使用 StrutsPrepareAndExecuteFilter |
| OGNL 表達式執行異常 | 屬性名稱錯誤、getter/setter 不符合規範 | 檢查 Action 類屬性命名、OGNL 表達式語法 |
File > Invalidate Caches / Restart)