国际化开发概述
软件的国际化:软件开发时,要使它能同时应对世界不同地区和国家的访问,并针对不同地区和国家的访问,提供相应的、符合来访者阅读习惯的页面或数据。 国际化(internationalization)又称为i18n(读法为i18n,据说是因为internationalization(国际化)这个单词从i到n之间有18个英文字母,i18n的名字由此而来)。
本文根据这张图来介绍SpringMVC实现国际化的过程:
1. 根据浏览器语言进行国际化配置
2. 根据语言切换进行国际化配置
接下来,写Demo:
首先我们来看看JAVA支持哪些国家和语言:
/**
* 查看Java支持的国家化语言
*/
public class LocaleList {
public static void main(String[] args) {
//获取java支持的所以国家和语言
Locale [] locales= Locale.getAvailableLocales();
//遍历打印
for(int index=0;index<locales.length;index++) {
System.out.println(locales[index].getDisplayCountry()+"="+
locales[index].getCountry()+" "+
locales[index].getDisplayLanguage()+"="+
locales[index].getLanguage());
}
}
}
现在java支持的国家和语言是非常多的,这里我只列出了两列,现在我们找出里面的中国和英国
- 中国=CN 中文=zh
- 英国=GB 英文=en
创建两个文本文件取名:
message_zh_CN.properties:
mesage_en_GB.properties:
简单说明下:两个文件的主要作用是让我们读取里面的信息, 然后知道转换的规则,中文在这个文本文件里面自动转换成了二进制文本。
创建测试类I18nDemo
public class I18nDemo {
public static void main(String[] args) {
//获取系统默认国家/语言环境
Locale locale = Locale.getDefault();
//加载资源文件
ResourceBundle bundle=ResourceBundle.getBundle("message",locale);
//使用资源文件
String hello = bundle.getString("hello");
System.out.println(hello);
}
}
运行:
如何使用占位符:
public static void main(String[] args) {
//获取系统默认国家/语言环境
Locale locale = Locale.getDefault();
//获取java支持的所以国家和语言
Locale [] locales= Locale.getAvailableLocales();
//遍历打印支持的国家的语言
for(int index=0;index<locales.length;index++) {
if(locales[index].getCountry().equals("GB")&&locales[index].getLanguage().equals("en")) {
locale=locales[index];
}
}
//加载资源文件
ResourceBundle bundle=ResourceBundle.getBundle("message",locale);
//使用资源文件
String hello = bundle.getString("hello");
System.out.println(hello);
//使用占位符
String message=bundle.getString("message");
message=MessageFormat.format(message, "zh",new Date());
System.out.println(message);
}
接下来我们开始学习,如何使用SpringMVC来实现国家化
1、创建一个动态页面:I8nLogin.jsp
2、更改mesage_en_GB.properties
这里让字符串显示为=后面的语言,=后面的字符串可以改为任何国家的语言
3、添加配置springMVC-servlet.xml
这里读取文本文件,知道我们需要转换为什么语言
<!-- 配置支持国际化 -->
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<!-- 设置国际化资源文件 -->
<property name="basename" value="message" />
</bean>
<!-- 配置默认加载资源 -->
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="en_GB" />
</bean>
4、创建I18nController
/**
* 登陆国际化页面控制器
*/
@Controller //指明页面控制器
public class I18nController {
@RequestMapping("i18nlogin") //请求页面处理方法
public String login(HttpServletRequest request,ModelMap modelMap) {
//获取资源文件
RequestContext requestContext=new RequestContext(request);
String username=requestContext.getMessage("username");
System.out.println(username);
String password=requestContext.getMessage("password");
System.out.println(password);
return "LoginSuccess";
}
}
这样就是使得在页面指定的字符串改为英文!