springmvc 国际化
目标:
一、在页面上根据浏览器语言设置的情况显示不同的文本内容、时间
1、编写国际化资源文件
i18n_en_US.properties
i18n_zh_CN.properties
i18n.properties
内容如下:
NotEmpty=..不能为空
Email=..不是一个合法的电子邮件
i18n.user=User
i18n.password=Password
NotEmpty=..不能为空
Email=..不是一个合法的电子邮件
i18n.user=用户名
i18n.password=密码
2、配置获取资源文件的bean ResourceBundleMessageResource 配置文件名basename 配置资源文件的默认编码格式defaultEncoding
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename" value="i18n"></property> <property name="defaultEncoding" value="utf-8"></property> </bean>
3、编写测试视图jsp,使用fmt标签引入
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<fmt:message key="i18n.user"></fmt:message>
<br>
<br>
<a href="i18n2">i18n2</a>
</body>
</html>
4、配置视图
<mvc:view-controller path="/i18n" view-name="i18n"/>
二、能够在bean中获取国际化资源文件对应的locale信息
1、在handler中映射连接,注入 bean ResourceBunderResourceMessage
2、通过Resource bean 的getMessage方法获取locale的信息
@RequestMapping("/i18n") public String testI18n(Locale locale) { System.out.println(resourceBundleMessageSource.getMessage("i18n.user", null, locale)); System.out.println(locale.getCountry()); return "i18n"; }
三、能够根据超链接切换locale,不再依赖于浏览器语言设置
原理:通过拦截器根据链接穿过来的name=locale信息获取locale,将locale存入session中,从session中取locale对象,使用locale对象
1、配置sessionLocaleResolver
<!-- 配置sessionLocaleResolver -->
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean>
2、配置LocaleChangeIntercepter
<!-- 配置LocaleChangeIntercepter -->
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"></bean>
</mvc:interceptors>
3、编写一个测试链接
<br> <br> <a href="i18n?locale=zh_CH">中文</a> <br> <br> <a href="i18n?locale=en_US">English</a>
邮箱:wangh_2@sina.com