关于国际化:
- 在页面上能够根据浏览器语言设置的情况对文本(不是内容),时间,数值进行本地化处理
- 可以在 bean 中获取国际化资源文件 Locale 对应的消息
- 可以通过超链接切换 Locale ,而不再依赖于浏览器的语言设置情况
解决:
- 使用 JSTL 的 fmt 标签
- 在 bean 中注入 ResourceBundleMessageSource 的实例,使用其对应的 getMessage 方法即可.
- 配置 LocalResolver 和 LocalChangeInterceptor .
No.1 Question
配置国际化资源文件,i18n_zh_CN.properties和i18n_en_US.properties
i18n.user=用户名
i18n.password=密码
i18n.user=User
i18n.password=Password
前端页面利用<fmt>标签进行国际化显示:
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<fmt:message key="i18n.user"></fmt:message>
<fmt:message key="i18n.password"></fmt:message>
No.2 Question
使用@RequestMapping的方式进行访问视图,使用ResourceBundleMessageSource进行获取国际化信息即可,代码如下
@Autowired
private ResourceBundleMessageSource messageSource;
@RequestMapping(value = "/i18n")
public String testI18n(Locale locale) {
String val = messageSource.getMessage("i18n.user", null, locale);
System.out.println(val);
return "i18n";
}
其中的Locale
由SpringMVC自动帮我们进行数据绑定,使用getMessage
方法即可获取国际化资源文件的值。
No.3 Question
超链接切换Locale,Struts2的原理:设置了一个i18n的拦截器,获取请求参数的Locale,吧Locale放到Session里面,每次用的时候直接从Session获取。
SpringMVC的原理:
配置
在springmvc.xml中加入如下代码:
<!-- 配置SessionLocaleResolver -->
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean>
<!-- 配置LocaleCHangeInterceptor -->
<mvc:interceptors>
<bean
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"></bean>
</mvc:interceptors>
一定要注意:SessionLocaleResolver的id
,不然会报错。
<a href="i18n?locale=zh_CN">中文</a>
<a href="i18n?locale=en_US">英文</a>
这样,直接通过超链接访问,即可以切换Locale,而不用通过网页的设置。