关于Struts2资源文件的配置
转载自:http://blog.csdn.net/Mount_here/archive/2009/02/03/3860700.aspx
最近在玩Struts2时,发现Struts2的资源文件配置的几个有趣的问题,特地跑来给大家分享。
据Struts2的文档,当由action加载页面时资源文件的的搜索顺序为:
ActionClass.properties Interface.properties (every interface and sub-interface) BaseClass.properties (all the way to Object.properties) ModelDriven's model (if implements ModelDriven), for the model object repeat from 1 package.properties (of the directory where class is located and every parent directory all the way to the root directory) search up the i18n message key hierarchy itself global resource properties 在了解这些后,我在struts.xml中如下配置:
<constant name="struts.action.extension" value="do" />
<constant name="struts.devMode" value="true" />
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<package name="practice" extends="struts-default">
<action name="index" class="com.opensymphony.xwork2.ActionSupport">
<result>index.jsp</result>
</action>
</package>
并把ActionSupport.properties放在相应包下面。因为所有的若不显示配置class, 默认的class 为ActionSupport,因此我用ActionSupport.properties,应该没问题吧。大家猜怎么着?
不行!
我怎么搞都不成,于是我要把它命名为package.properties,应为根据资源文件的搜索顺序,若找不到相应action的资源文件,应该找包级别的资源文件。结果呢?
还是不行!
于是我又配置了struts.properties文件,指定全局资源:struts.custom.i18n.resources=globalMessages
结果可以了!
难道首页的多语言必须配置在全局资源文件中吗?放在action级别和包级别都不起作用,那该如何是好呢?
我想到的解决办法是,写一个action,如:BaseAction继承ActionSupport,抽象出一些公用的东西来,或干脆为空,
然后让我们的其它action都继承BaseAction,这样的话在struts.xml中如下配置:
<constant name="struts.action.extension" value="do" />
<constant name="struts.devMode" value="true" />
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<package name="practice" extends="struts-default">
<action name="index" class="wbw.practice.actions.BaseAction">
<result>index.jsp</result>
</action>
</package>
然后创建BaseAction.properties文件放在相应包下面就可以了;不用BaseAction.proerties,用package.properties也Ok!
据此应用struts2的资源文件应注意以下两点:
-
只有通过自定义的Action到达的页面,资源文件才起作用。也就是说:
和
<result>index.jsp</result> </action>是一样的,资源文件不会被应用的!
-
struts2文档中的资源文件搜索顺序的第一条:ActionClass.proerpties中的ActionClass必须是自己写的 ActionClass.
在这里缓缓走过,很为楼主钻研精神感动,也感谢楼主分享。 :idea: