概述
国际化并不是对内容进行国际化,而是对本身要显示的文字进行国际化,需要在SpringIOC容器中配置国际化资源文件的bean,国际化是具体通过Locale完成。
SpringMVC为国际化提供了本地化拦截器和本地化解析器,以便完成通过超链接切换方式完成国际化。
- 本地化解析器: SessionLocaleResovler
- 本地化拦截器:LocaleChangeInterceptor
过程
通过切换超链接完成国际化
1. 导入jar包
jstl.jar
standard.jar
2. 配置国际化资源文件
- i18n.properties
i18n.name=username
i18n.pass=password
- i18n_zh_CN.properties
i18n.name=\u7528\u6237\u540D
i18n.pass=\u5BC6\u7801
- i18n_en_US.properties
i18n.name=USERNAME
i18n.pass=PASSWORD
3. 配置国际资源文件的bean
<!-- 配置国际化资源文件的bean -->
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="i18n"></property>
</bean>
4. 配置本地化拦截器和本地化解析器
<!-- 配置本地化解析器 -->
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
</bean>
<!-- 本地化拦截器 -->
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"></bean>
</mvc:interceptors>
5. 编写index.jsp( 参数locale )
<a href="${pageContext.request.contextPath}/testLocale?locale=zh_CN">中文</a>
<br>
<a href="${pageContext.request.contextPath}/testLocale?locale=en_US">English</a>
6. 编写请求处理器
@Controller
public class LocaleController {
@RequestMapping("/testLocale")
public String testLocale() {
return "success";
}
}
7. 编写success.jsp
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> //引入标签库
<body>
<fmt:message key="i18n.name"></fmt:message>
<fmt:message key="i18n.pass"></fmt:message>
</body>
8. 显示结果
点击中文或英文显示不同的用户名和密码