1.创建.properties配置文件
首先在IDE中创建Web Project,在src根目录下创建两个配置文件:
MessagesBundle_fr_FR.properties
greetings = Bonjour.
farewell = Au revoir.
inquiry =Comment allez-vous?
MessagesBundle.properties
greetings = Hello
farewell = Goodbye
inquiry =How are you?
注意:
配置文件的命名是有讲究的,格式为下划线连接着三个部分:
“自定义名字”“语言代码” “国家代码”
2.在Web.xml中定义context-param
<!-- Define the basename for a resource bundle for I18N -->
<context-param>
<param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
<param-value>MessagesResources</param-value>
</context-param>
3.创建一个类编写Java代码
import java.util.Locale;
import java.util.ResourceBundle;
public class I18nTest {
public static void main(String[] args) {
String language;
String country;
if (args.length != 2) {
language = new String("en");
country = new String("US");
} else {
language = new String(args[0]);
country = new String(args[1]);
}
Locale currentLocale;
ResourceBundle messages;
currentLocale = new Locale(language, country);
messages = ResourceBundle.getBundle("MessagesBundle_fr_FR", currentLocale);
System.out.println(messages.getString("greetings"));
System.out.println(messages.getString("inquiry"));
System.out.println(messages.getString("farewell"));
}
}