国际化概述
- 国际化的需求:
- 在页面中根据浏览器的语言设置,对文本,数值,时间,进行本地化处理
- 可以在bean中获取国际化资源文件Locale对应的信息
- 可以根据超链接切换Locale.而不在依赖于浏览器语言的设置.
- 解决的方式:
- 使用JSTL的<fmt>标签实现不同语言的显示
- 在SpringMVC的IOC容器中配置ResourceBundleMessagesSource的实例,使用其对应的getMessage()方法
- 配置 LocalResolver(本地转换器)和LocalChangeInterceptor(本地拦截器)
解决前两个问题
在浏览器中现实国际化信息
- 在SpringMVC的配置文件中配置 ResourceBundleMessageSource
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="i18n"/>
</bean>
- i18n.properties
i18n.username=UserName
i18n.password=Password
- i18n_zh_CN.properties(用于显示中文的信息)
i18n.username=用户名
i18n.password=密码
- i18n_en_US.properties(用于显示英文信息)
i18n.username=UserName
i18n.password=Password
<%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>国际化显示</title>
</head>
<body>
<fmt:message key="i18n.password"/><br/>
<fmt:message key="i18n.username"/><br/>
</body>
</html>
<mvc:view-controller path="/i18n" view-name="i18n"/>
在Bean中接收国际化资源文件的信息
- 在需要读取资源文件的Bean类中添加 ResourceBundleMessageSource 实例化对象引用
@Autowired
private ResourceBundleMessageSource messageSource;
- 在请求路径映射方法中添加一个 Locale 的入参,使用ResourceBundleMessageSource 的getMessage()方法获取资源文件中的信息
@RequestMapping("/testI18n")
public String testI18n(Locale locale){
String name = this.messageSource.getMessage("i18n.username",null,locale);
String password = this.messageSource.getMessage("i18n.password",null,locale);
System.out.println(name);
System.out.println(password);
return "i18n";
}
通过链接切换Locale
- 通过配置本地化拦截器和本地化解析器
- 如果没有指定显示本地化解析器SpringMVC默认使用的是AcceptHeaderLocaleResolver,根据请求头"Accept-Language"参数确定本地化类型
- 如果希望通过链接切换Locale 则需要配置SessionLocaleResolver,根据session属性中的信息确定本地化类型
- 配置SpringMVC的配置文件
-
这里需要注意的是:配置SessionLocaleResolver的时候,id值必须为localeResolver,否则会出现异常
- Cannot change HTTP accept header - use a different locale resolution strategy
- 因为在DispatcherServlet初始化localeResolver的时候,是根据"localeResolver"这个名称从IOC容器中获取的
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean>
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"/>
</mvc:interceptors>
- 测试:定义两个超链接每个超链接包含"locale"这个参数,
<br/>
<a href="testI18n?locale=zh_CN">中文</a>
<br/>
<a href="testI18n?locale=en_US">英文</a>