代码下载
http://pan.baidu.com/s/1sjNQmfF
Maven依赖
1
2
3
4
5
6
7
8
9
10
11
|
<
properties
>
<
springframework
>4.0.5.RELEASE</
springframework
>
</
properties
>
<
dependencies
>
<!-- Spring web mvc -->
<
dependency
>
<
groupId
>org.springframework</
groupId
>
<
artifactId
>spring-webmvc</
artifactId
>
<
version
>${springframework}</
version
>
</
dependency
>
</
dependencies
>
|
项目截图
在Spring应用中,国际化的配置比较简单,下面四步完成国际化的快速配置
第一步,配置messageSource和localeResolver
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<!-- 配置国际化资源文件路径 -->
<
bean
id
=
"messageSource"
class
=
"org.springframework.context.support.ResourceBundleMessageSource"
>
<
property
name
=
"basename"
>
<!-- 定义消息资源文件的相对路径 -->
<
value
>messages/message</
value
>
</
property
>
</
bean
>
<!-- 基于Cookie的本地化解析器 -->
<
bean
id
=
"localeResolver"
class
=
"org.springframework.web.servlet.i18n.CookieLocaleResolver"
>
<
property
name
=
"cookieMaxAge"
value
=
"604800"
/>
<
property
name
=
"defaultLocale"
value
=
"zh_CN"
/>
<
property
name
=
"cookieName"
value
=
"Language"
></
property
>
</
bean
>
<!-- 基于Session的本地化解析器 -->
<!--<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" />-->
|
第二步,编写message_*.properties
message_en.properties
1
2
3
4
5
6
7
|
hi=hello
something=The People's Republic of China
Chinese=Chinese
English=English
index=Index
welcome=Welcome
OtherPage=Other Page
|
message_zh_CN.properties(汉字已转成unicode码)
1
2
3
4
5
6
7
|
hi=\u4F60\u597D
something=\u4E2D\u534E\u4EBA\u6C11\u5171\u548C\u56FD
Chinese=\u4E2D\u6587
English=\u82F1\u6587
OtherPage=\u5176\u4ED6\u9875\u9762
index=\u9996\u9875
welcome=\u6B22\u8FCE
|
第三步,页面引入spring标签库
引入
1
|
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
|
使用
1
|
<
spring:message
code
=
"welcome"
></
spring:message
>
|
第四步,切换语言
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
@Autowired
CookieLocaleResolver resolver;
//@Autowired SessionLocaleResolver resolver;
/**
* 语言切换
*/
@RequestMapping
(
"language"
)
public
ModelAndView language(HttpServletRequest request,HttpServletResponse response,String language){
language=language.toLowerCase();
if
(language==
null
||language.equals(
""
)){
return
new
ModelAndView(
"redirect:/"
);
}
else
{
if
(language.equals(
"zh_cn"
)){
resolver.setLocale(request, response, Locale.CHINA );
}
else
if
(language.equals(
"en"
)){
resolver.setLocale(request, response, Locale.ENGLISH );
}
else
{
resolver.setLocale(request, response, Locale.CHINA );
}
}
return
new
ModelAndView(
"redirect:/"
);
}
|
已完成国际化的配置,其中请注意SessionLocaleResolver和CookieLocaleResolver的区别,很显然,通过Session只能对当前的会话有效,Cookie则对Cookie有效期内的会话都有效。在使用Cookie的时候,需要设置Cookie的过期时间,否则关闭浏览器之后,Cookie即失效了,没有达到目的。当然,也可以保存用户的语言设置信息到数据库,用户登录之后即可将语言改变成用户设置的语言。
运行效果截图:
<转载请注明来源:http://www.xdemo.org/spring-i18n/ >