# 国际化支持
# 国际化概述
在常规系统开发中,面向国际化的系统或者网站难免会使用到国际化的支持,因为很多网站或者系统是面向国外的用户,因为框架在设计之初就支持了国际化的部署,可以选择不同的语言展示系统,系统已经支持多语言国际化,下面我们详细介绍如何使用。
# 国际化配置
针对国际化设置,我们新建了国际化配置文件 I18nConfig
可以在配置文件中设置默认支持语言以及设置其他国际化语言,配置文件如下:
package com.javaweb.common.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import java.util.Locale;
/**
* 国际化配置文件
*/
@Configuration
public class I18nConfig implements WebMvcConfigurer {
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver slr = new SessionLocaleResolver();
// 默认语言
slr.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);
return slr;
}
@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
// 参数名
lci.setParamName("lang");
return lci;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
}
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
如上述国际化配置文件,系统默认设置的是简体中文
,如下:
// 默认语言,英文可以设置Locale.US
slr.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);
1
2
2
特别提醒
系统默认设置的是 简体中文
语言,也可以根据需求设置其他语言的支持
# 国际化资源
除了上述设置外,我们还需要在系统 application.yml
中配置国际化支持的相关配置,设置国际化文件资源的位置及编码等信息,修改配置文件中的basename国际化文件位置,默认是i18n路径下messages文件
(比如现在国际化文件是xx_zh_CN.properties、xx_en_US.properties,那么basename配置应为是i18n/xx,如下所示:
spring:
# 自定义国际化配置
messages:
# 国际化资源文件路径
basename: i18n/messages
encoding: UTF-8
1
2
3
4
5
6
7
2
3
4
5
6
7
- i18n目录文件下定义资源文件
- 英文配置
messages_en_US.properties
user.login.username=User name
user.login.password=Password
user.login.code=Security code
user.login.remember=Remember me
user.login.submit=Sign In
1
2
3
4
5
2
3
4
5
- 中文简体
messages_zh_CN.properties
user.login.username=用户名
user.login.password=用户密码
user.login.code=验证码
user.login.remember=记住我
user.login.submit=登录
1
2
3
4
5
2
3
4
5