三、改变struts.xml默认路径后web.xml如何配置

在struts2框架中struts.xml是应当放到src的根目录,程序编译后会将struts.xml放到WEB-INF/classes目录下。

Struts2在web.xml中的一般配置如下:

<filter>
        <filter-name>struts2</filter-name>
        <filter-class>
             org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
        </filter-class>        
</filter>
<filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
</filter-mapping>

根据配置就会先后加载struts-default.xml、struts-plugin.xml、然后自动加载classes目录下的struts.xml 。

但是有时为了协作开发或方便管理,有时可能需要把struts.xml放到其他位置,如下图所示:

这个时候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,config/struts2/struts.xml
                </param-value>
        </init-param>        
</filter>
<filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
</filter-mapping>

我们可以通过上述web.xml的配置找到struts.xml文件的位置,但在这里有人可能会疑问了,那为什么要struts-default.xml也需要指定呢?因为我们改变了struts.xml文件的位置后,如果不手动指定,就不会自动加载。就会出现下面的异常:


 

所以需要特别注意struts2默认加载的文件,如struts-default.xml,struts-plugin.xml都需要在

<param-value/>中重新指定一下。

温馨提示:在上述的程序中,大家可能注意我重新指定了struts-default.xml而没有写struts-plugin.xml,那是因为我这个项目没有用到插件,引用的是项目的基本jar,基本Jar中是没有struts-plugin.xml配置文件的。这个配置文件是在插件jar包中。如图:


 任意解压缩一个Jar包即可发现:


所以我们需要清楚虽然配置文件的加载顺序是
struts-default.xml、struts-plugin.xml、struts.xml,但是如果没有插件的应用那么就是struts-default.xml、struts.xml的顺序。这就是上述显性指定时没有指定struts-plugin.xml的原因。

当然如果不想在web.xml文件中指定struts-default.xml,struts-plugin.xml的话,也可在struts.xml文件中通过include将原有配置文件包含进来。

<struts>	
    <include file="struts-default.xml" ></include>	
    <package name="example" namespace="/" extends="struts-default">
        <action name="login" class="com.yanln.test.action.LoginAction">
            <result name="success">success.jsp</result>           
        </action>
    </package>
</struts>

注意:每个人的编程习惯是不一样的,有的人可能把配置文件习惯如下方式放置


 那么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,../config/struts2/struts.xml
                </param-value>        	
        </init-param>        
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

 主要原因是struts2默认会到WEB-INF/classes目录下去找配置文件。

 
 
 

猜你喜欢

转载自yanln.iteye.com/blog/2189816