多くの場合、アプリケーション内のすべてのクラスで使用可能なメッセージを格納するために、グローバルリソースバンドル(プロパティファイル)が必要になることがあります。
ダウンロードする – リンク://wp-content/uploads/2010/06/Struts2-global-resource-bundle-Example.zip[Struts2-global-resource-bundle-Example.zip]
Struts 2では、グローバルリソースバンドルを設定する3つの方法があります。
1. struts.properties
“struts.properties”ファイル内のグローバルリソースバンドルを設定します。ここでは、 ”
global.properties
“という名前のプロパティファイルをグローバルリソースバンドルとして定義します。
struts.custom.i18n.resources = global
複数のリソースバンドルの場合は、プロパティファイルをコンマで区切ります。
struts.custom.i18n.resources = global, another-properties-file
2. struts.xml
あるいは、グローバルリソースバンドルを
struts.xml
設定ファイルの定数値として設定することもできます。
<struts> <constant name="struts.custom.i18n.resources" value="global"/> </struts>
3.リスナー
最後の方法は、サーブレット・リスナーを使用してグローバル・リソース・バンドルとしてプロパティ・ファイルをロードすることです。
package com.mkyong.common.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import com.opensymphony.xwork2.util.LocalizedTextUtil;
public class GlobalMessagesListener implements ServletContextListener {
private static final String DEFAULT__RESOURCE = "global";
public void contextInitialized(ServletContextEvent arg0) {
LocalizedTextUtil.addDefaultResourceBundle(DEFAULT__RESOURCE);
}
public void contextDestroyed(ServletContextEvent arg0) {
}
}
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app__2__3.dtd" >
<web-app>
<display-name>Struts 2 Web Application</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/** </url-pattern>
</filter-mapping>
<listener>
<listener-class>
com.mkyong.common.listener.GlobalMessagesListener
</listener-class>
</listener>
</web-app>