Struts 2 覆盖资源消息键

Struts 2 override resource messages keys

考虑这个

<constant name="struts.custom.i18n.resources"
        value="messages/default,messages/customize" />

default.properties内容是

label.sample = Default Sample

而customize.properties内容是

//Duplicate key
label.sample = Customize Sample

调用 <s:text name="label.sample"> 将导致 Customize Sample 如果我们查看上面的信任 i18n,这似乎是正确的行为,因为我们首先定义了默认值,然后定义了自定义,因此自定义属性中的键将覆盖键默认。

现在我们尝试动态覆盖自定义消息。所以

   <!--The customize is removed -->
    <constant name="struts.custom.i18n.resources"
            value="messages/default" />

在一些像启动 servlet 的地方,我们添加自定义消息为:

LocalizedTextUtil.clearDefaultResourceBundles();
LocalizedTextUtil.addDefaultResourceBundle("messages/customize");

这不行!作为替代方案,如果我们从 i18n 属性 中删除默认值并按如下方式执行,我们将获得自定义值

LocalizedTextUtil.clearDefaultResourceBundles();
LocalizedTextUtil.addDefaultResourceBundle("messages/default");
LocalizedTextUtil.addDefaultResourceBundle("messages/customize");

是否可以在 xml 中保留默认属性列表并仅在 运行 时间添加自定义属性


这就是我们需要它的原因 我们正在开发和托管一个出售给许多客户的网络应用程序。该应用程序有一条默认消息。我们的一位客户可能想要更改某些应用程序默认消息,而其他客户则不想。所以我们有一个自定义消息的文件夹,让每个银行覆盖自己的消息。

我们为客户提供以下文件夹结构:

+messages
  -resources_fa_IR.properties
  -resources_en_US.properties 
+customer1
   -customize_fa_IR.properties
   -customize_en_US.properties
+customer2
   -customize_fa_IR.properties
   -customize_en_US.properties

并在 StartUpSerlvet

//Set customer customize messages
LocalizedTextUtil.addDefaultResourceBundle("messages/" + activeCustomer+"/customize"); 

它不起作用,因为您的自定义 ServletContextListener 在 S2 添加来自 struts.custom.i18n.resources 的默认资源包之前运行。

解决方案是从某个地方执行LocalizedTextUtil.addDefaultResourceBundle S2 添加所有默认资源包后执行的内容。 例如,您可以扩展 StrutsPrepareAndExecuteFilter 并在 postInit 方法中执行。