文章目录
(1)创建并编写国际化配置文件
- 在resources下新建i18n文件夹,并以下图方式创建三个配置文件,分别命名为:index.properties,index_en_US.properties,index_zh_CN.properties
- 编写国际化配置文件
(2)使用ResourceBundleMessageSource管理国际化资源文件
SpringBoot已经自动配置了管理国际化资源文件的组件
@Configuration
@ConditionalOnMissingBean(
value = {MessageSource.class},
search = SearchStrategy.CURRENT
)
@AutoConfigureOrder(-2147483648)
@Conditional({MessageSourceAutoConfiguration.ResourceBundleCondition.class})
@EnableConfigurationProperties
public class MessageSourceAutoConfiguration {
private static final Resource[] NO_RESOURCES = new Resource[0];
public MessageSourceAutoConfiguration() {
}
@Bean
@ConfigurationProperties(
prefix = "spring.messages"
)
public MessageSourceProperties messageSourceProperties() {
return new MessageSourceProperties();
}
@Bean
public MessageSource messageSource(MessageSourceProperties properties) {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
if (StringUtils.hasText(properties.getBasename())) {
messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(properties.getBasename())));
}
if (properties.getEncoding() != null) {
messageSource.setDefaultEncoding(properties.getEncoding().name());
}
messageSource.setFallbackToSystemLocale(properties.isFallbackToSystemLocale());
Duration cacheDuration = properties.getCacheDuration();
if (cacheDuration != null) {
messageSource.setCacheMillis(cacheDuration.toMillis());
}
messageSource.setAlwaysUseMessageFormat(properties.isAlwaysUseMessageFormat());
messageSource.setUseCodeAsDefaultMessage(properties.isUseCodeAsDefaultMessage());
return messageSource;
}
protected static class ResourceBundleCondition extends SpringBootCondition {
private static ConcurrentReferenceHashMap<String, ConditionOutcome> cache = new ConcurrentReferenceHashMap();
protected ResourceBundleCondition() {
}
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
String basename = context.getEnvironment().getProperty("spring.messages.basename", "messages");
ConditionOutcome outcome = (ConditionOutcome)cache.get(basename);
if (outcome == null) {
outcome = this.getMatchOutcomeForBasename(context, basename);
cache.put(basename, outcome);
}
return outcome;
}
。。。
(3)在配置文件 application.properties 中指定国际化资源文件的文件夹及基础文件
# 指定国际化资源文件的文件夹及基础文件
spring.messages.basename=i18n.login
(4)* 编写自定义的Locale区域解析器
/**
* 编写自定义的 Locale区域解析器:
* SpringBoot默认的Locale解析器是根据请求头的区域信息进行解析的(浏览器语言)
* 使用自定义的Locale解析器对url的区域信息进行解析达到点击切换区域效果
* 一旦我们自定义的区域解析器注册到Spring容器中,则SpringBoot提供的将不自动注册
* */
public class MyLocaleResolver implements LocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest request) {
String lg = request.getParameter("lg");
Locale locale = Locale.getDefault();
if(!StringUtils.isEmpty(lg)){
String[] split = lg.split("_");
locale = new Locale(split[0], split[1]);
}
return null;
}
@Override
public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
}
}
(5)* 注册我们自定义的区域解析器
/*
* 扩展SpringMVC
* SpringBoot2使用的Spring5,因此将WebMvcConfigurerAdapter改为WebMvcConfigurer
* 使用WebMvcConfigurer扩展SpringMVC好处既保留了SpringBoot的自动配置,又能用到我们自己的配置
* */
//使用WebMvcConfigurationAdapter 可以扩展SpringMvC的功能
//@EnableWebMvc //如果我们需要全面接管SpringBoot中的SpringMVC配置则开启此注解,
//开启后,SpringMVC的自动配置将会失效。
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
/*
* <mvc:view-controller path="/" view-name="home"/>
* */
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// 设置对“/”的请求映射到hello
// 如果没有数据返回到页面,没有必要用控制器方法对请求进行映射
registry.addViewController("/").setViewName("hello");
registry.addViewController("/login").setViewName("login");
}
//注册我们自定义的区域解析器,一旦将我们的区域解析器注册到Spring容器中则
//SpingBoot默认提供的区域解析器将不会自动注册
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
(6)视图中引用国际化内容
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>国际化测试页面</title>
</head>
<body>
<h1 th:text="#{username}"></h1>
</body>
</html>
最后你就可以通过切换浏览器语言查看不同的效果。