目标:html
1、在页面上根据浏览器语言设置的状况显示不一样的文本内容、时间java
一、编写国际化资源文件web
i18n_en_US.propertiesspring
i18n_zh_CN.properties浏览器
i18n.propertiessession
内容以下:mvc
NotEmpty=..不能为空
Email=..不是一个合法的电子邮件
i18n.user=User
i18n.password=Password
NotEmpty=..不能为空
Email=..不是一个合法的电子邮件
i18n.user=用户名
i18n.password=密码
二、配置获取资源文件的bean ResourceBundleMessageResource 配置文件名basename 配置资源文件的默认编码格式defaultEncodingapp
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename" value="i18n"></property> <property name="defaultEncoding" value="utf-8"></property> </bean>
三、编写测试视图jsp,使用fmt标签引入jsp
<%@ 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>
四、配置视图测试
<mvc:view-controller path="/i18n" view-name="i18n"/>
2、可以在bean中获取国际化资源文件对应的locale信息
一、在handler中映射链接,注入 bean ResourceBunderResourceMessage
二、经过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"; }
3、可以根据超连接切换locale,再也不依赖于浏览器语言设置
原理:经过拦截器根据连接穿过来的name=locale信息获取locale,将locale存入session中,从session中取locale对象,使用locale对象
一、配置sessionLocaleResolver
<!-- 配置sessionLocaleResolver -->
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean>
二、配置LocaleChangeIntercepter
<!-- 配置LocaleChangeIntercepter -->
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"></bean>
</mvc:interceptors>
三、编写一个测试连接
<br> <br> <a href="i18n?locale=zh_CH">中文</a> <br> <br> <a href="i18n?locale=en_US">English</a>