struts2中改變struts.xml默認路徑 或可能遇到的問題

struts2.X配置文件默認存放路徑在/WEB-INF/classes目錄下,即將struts.xml放在src的目錄下。

但是爲了方便管理,開發人員把struts.xml放到其他位置,處理方法如下。

首先要明白struts2加載配置文件都是從自己的jar包和/WEB-INF/classes兩個默認的位置加載的。

若修改struts2.x配置文件的存放位置,在web.xml配置過慮器時,具體配置如下:
 

1 <filter>
2     <filter-name>struts2</filter-name>
3     <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
4     <init-param
5         <param-name>config</param-name
6         <param-value>struts-default.xml,struts-plugin.xml,struts/struts.xml</param-value>
7     </init-param>
8 </filter>

 

注意點1

若設置了<param-name>config</param-name>參數,那struts-default.xml等原來struts2默認加載的文件也要手動指定,否則不會自動加載。

 

注意點2

struts-plugin.xml也需要指定。因爲在struts2使用2.1.6版本時:

若需要和spring集成的話,struts2-spring-plugin-2.1.6.jar中有struts-plugin.xml這個文件。

若struts2要支持json的話, json-plugin-0.34.jar中也有一個叫struts-plugin.xm的文件。

因此這個文件也是要加載的。

 

注意點3

採用相對/WEB-INF/classes的相對路徑。本例放在了/WEB-INF/classes/struts目錄下。當然也可以寫成classpath:struts/struts.xml

 

注意點4

若不在這裏配置struts-default.xml,struts-plugin.xml,也可以在struts.xml文件中添加include標籤將兩個文件包括進去。

<include file="struts-default.xml" />和<include file="struts-plugin.xml" />

 

注意點5

使用<include file="..." />標籤添加其他子配置文件時,file屬性也要是一個相對/WEB-INF/classes的路徑。

若子配置文件路徑是/WEB-INF/classes/configs/struts/student/struts-config.xml的話,

file屬性值應該寫configs/struts/student/struts-config.xml。

若有多個子配置文件可以採用掃描的方式<include file="configs/struts/*/*.xml" />


可能遇到的問題:

錯誤
警告: Could not find action or result
      There is no Action mapped for namespace / and action name hello. - [unknown location]


??????不要着急,很正常!

 

 

  • 仔細看看Tomcat的啓動日誌,依然可以發現一個失敗信息:

1 2011-7-17 20:15:36 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
2 信息: Unable to locate configuration files of the name struts.xml, skipping

 

爲什麼指定了自己的struts.xml文件路徑依然訪問不到呢?

原因依然在struts加載配置文件的方式,struts並不是獲取的配置文件相對應用(項目)的路徑,而是相對src,對於web是相對/WEB-INF/classes文件夾的路徑,現在知道了最終的解決方案了?

對了,就是把web.xml中的[/WEB-INF/struts.xml]改成 [../struts.xml],即使用相對/WEB-INF/classes文件夾的路徑!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章