struts2 配置文件位置,不使用默认路径的配置

参考:https://www.cnblogs.com/javabg/p/7095301.html

struts2.X配置文件默认存放路径在/WEB-INF/classes目录下,即将struts.xml放在src的目录下。

但是为了方便管理,开发人员把struts.xml放到其他位置,处理方法如下。

首先要明白struts2加载配置文件都是从自己的jar包和/WEB-INF/classes两个默认的位置加载的。

若修改struts2.x配置文件的存放位置,在web.xml配置过虑器时,具体配置如下:

<filter>
	<filter-name>struts2</filter-name>
	<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
	<init-param> 
		<param-name>config</param-name> 
		<param-value>struts-default.xml,struts-plugin.xml,struts/struts.xml</param-value>
	</init-param>
</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]

为什么指定了自己的struts.xml文件路径依然访问不到呢?
原因依然在struts加载配置文件的方式,struts并不是获取的配置文件相对应用(项目)的路径,而是相对src,对于web是相对/WEB-INF/classes文件夹的路径,现在知道了最终的解决方案了?
对了,就是把web.xml中的[/WEB-INF/struts.xml]改成 [../struts.xml],即使用相对/WEB-INF/classes文件夹的路径!

猜你喜欢

转载自blog.csdn.net/qq_39005790/article/details/80824079