12. SpringBoot国际化
1)、编写国际化配置文件;
2)、使用ResourceBundleMessageSource管理国际化资源文件
3)、在页面使用fmt:message取出国际化内容
步骤:
1)、编写国际化配置文件,抽取页面需要显示的国际化消息
国际化文件是peroperties文件

自动识别国际化视图

通过国际化视图创建国际化配置文件

同时对比编辑多个配置文件

配置国际化文件路径:
spring.messages.basename=static.i18n.login
@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())) {
//设置国际化文件的基础名称(去掉语言_国家代{zh_CN})的):即默认是message.properties,上图中我们起的名称是login.properties
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) {
//自定义的话就用此属性:spring.messages.basename来指定,默认叫message.propertie
//我们上图的需要指定为:spring.messages.basename=login
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;
} private ConditionOutcome getMatchOutcomeForBasename(ConditionContext context, String basename) {
Builder message = ConditionMessage.forCondition("ResourceBundle", new Object[0]);
String[] var4 = StringUtils.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(basename));
int var5 = var4.length; for(int var6 = 0; var6 < var5; ++var6) {
String name = var4[var6];
Resource[] var8 = this.getResources(context.getClassLoader(), name);//类路径
int var9 = var8.length; for(int var10 = 0; var10 < var9; ++var10) {
Resource resource = var8[var10];
if (resource.exists()) {
return ConditionOutcome.match(message.found("bundle").items(new Object[]{resource}));
}
}
} return ConditionOutcome.noMatch(message.didNotFind("bundle with basename " + basename).atAll());
} private Resource[] getResources(ClassLoader classLoader, String name) {
String target = name.replace('.', '/'); try {
//类路径下的 message.properties 和 messages_zh_CN.properties 或 自己指定的xxxx.properties 、xxxx.preperties
return (new PathMatchingResourcePatternResolver(classLoader)).getResources("classpath*:" + target + ".properties");
} catch (Exception var5) {
return MessageSourceAutoConfiguration.NO_RESOURCES;
}
}
}
}
public class MessageSourceProperties {
private String basename = "messages";//我们的配置文件可以直接放在类路径下,默认名称叫message.properties
private Charset encoding;
@DurationUnit(ChronoUnit.SECONDS)
private Duration cacheDuration;
private boolean fallbackToSystemLocale;
private boolean alwaysUseMessageFormat;
private boolean useCodeAsDefaultMessage;
public MessageSourceProperties() {
this.encoding = StandardCharsets.UTF_8;
this.fallbackToSystemLocale = true;
this.alwaysUseMessageFormat = false;
this.useCodeAsDefaultMessage = false;
}
public String getBasename() {
return this.basename;
}
public void setBasename(String basename) {
this.basename = basename;
}
......
}


<!-- 中英文切换链接 -->
<a class="btn btn-sm" th:href="@{/index.html(l='zh_CN'}">中文</a>
<a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a>
是根据浏览器的默认语言识别的

不过取出来的中文有乱码

IDEA中将UTF-8自动组转为ASSIC码

File ——》 settings 里的设置只是针对当前项目的设置,要想设置全局的

Settins ——》Other Settings ——》Default Settings 设置全局的默认设置

然后重新编辑有乱码的properties文件
根据浏览器的默认语言设置自动区分国际化字段的显示

默认请求头里会有语言的信息

切换默认的语言,请求头中排在第一位的也就变了

实现原理:
国际化Locale(区域信息对象);LocaleResolver(获取区域信息对象)
public class WebMvcAutoConfiguration {
public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer, ResourceLoaderAware {
@Bean
@ConditionalOnMissingBean //当项目中没有区域解析器的时候,才执行这个SprigBoot默认的配置,所以可以自定义
@ConditionalOnProperty(
prefix = "spring.mvc",
name = {"locale"}
)
//
public LocaleResolver localeResolver() {
//默认从配置文件中获取
if (this.mvcProperties.getLocaleResolver() == org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties.LocaleResolver.FIXED) {
return new FixedLocaleResolver(this.mvcProperties.getLocale());
} else {//如果配置文件中没有,则从HttpRequest的header中获取
AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
localeResolver.setDefaultLocale(this.mvcProperties.getLocale());
return localeResolver;
}
}
}
public class AcceptHeaderLocaleResolver implements LocaleResolver {
public Locale resolveLocale(HttpServletRequest request) {
Locale defaultLocale = this.getDefaultLocale();
if (defaultLocale != null && request.getHeader("Accept-Language") == null) {
return defaultLocale;
} else {
Locale requestLocale = request.getLocale();
List<Locale> supportedLocales = this.getSupportedLocales();
if (!supportedLocales.isEmpty() && !supportedLocales.contains(requestLocale)) {
Locale supportedLocale = this.findSupportedLocale(request, supportedLocales);
if (supportedLocale != null) {
return supportedLocale;
} else {//如果默认的区域解析器为空,则从requset请求头中获取
return defaultLocale != null ? defaultLocale : requestLocale;
}
} else {
return requestLocale;
}
}
}
}
自定义区域解析器,点击链接切换国际化
public class MyLocaleResolver implements LocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest request) {
String l = request.getParameter("l");
Locale locale = Locale.getDefault();
if (!StringUtils.isEmpty(l)) {
String[] split = l.split("_");
locale = new Locale(split[0], split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest httpServletRequest, @Nullable HttpServletResponse httpServletResponse, @Nullable Locale locale) {
}
}
//将自定义的区域解析器加入到容器中来
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
12. SpringBoot国际化的更多相关文章
- SpringBoot 国际化配置,SpringBoot Locale 国际化
SpringBoot 国际化配置,SpringBoot Locale 国际化 ================================ ©Copyright 蕃薯耀 2018年3月27日 ht ...
- springboot国际化与@valid国际化支持
springboot国际化 springboot对国际化的支持还是很好的,要实现国际化还简单.主要流程是通过配置springboot的LocaleResolver解析器,当请求打到springboot ...
- 【spring 国际化】springMVC、springboot国际化处理详解
在web开发中我们常常会遇到国际化语言处理问题,那么如何来做到国际化呢? 你能get的知识点? 使用springgmvc与thymeleaf进行国际化处理. 使用springgmvc与jsp进行国际化 ...
- SpringBoot 国际化
一.配置文件 二.application.properties 文件( 让国际化的文件被 SpringBoot 识别 ) spring.messages.basename=i18n.login 三.h ...
- 12.SpringBoot+MyBatis(XML)+Druid
转自:https://www.cnblogs.com/MaxElephant/p/8108342.html 主要是在Spring Boot中集成MyBatis,可以选用基于注解的方式,也可以选择xml ...
- Springboot国际化信息(i18n)解析
国际化信息理解 国际化信息也称为本地化信息 . Java 通过 java.util.Locale 类来表示本地化对象,它通过 “语言类型” 和 “国家/地区” 来创建一个确定的本地化对象 .举个例子吧 ...
- 补习系列(12)-springboot 与邮件发送【华为云技术分享】
目录 一.邮件协议 关于数据传输 二.SpringBoot 与邮件 A. 添加依赖 B. 配置文件 C. 发送文本邮件 D.发送附件 E. 发送Html邮件 三.CID与图片 参考文档 一.邮件协议 ...
- 【SpringBoot】SpringBoot 国际化(七)
本周介绍SpringBoot项目的国际化是如何处理的,阅读本章前请阅读[SpringBoot]SpringBoot与Thymeleaf模版(六)的相关内容 国际化原理 1.在Spring中有国际化Lo ...
- 补习系列(12)-springboot 与邮件发送
目录 一.邮件协议 关于数据传输 二.SpringBoot 与邮件 A. 添加依赖 B. 配置文件 C. 发送文本邮件 D.发送附件 E. 发送Html邮件 三.CID与图片 参考文档 一.邮件协议 ...
随机推荐
- [工作相关] 一个虚拟机上面的SAP4HANA的简单使用维护
1.公司组织竞品分析, 选择了SAP的 SAP4HANA作为竞品 这边协助同事搭建了SAP4HANA的测试环境: 备注 这个环境 应该是同事通过一些渠道获取到的. 里面是基于这个虚拟机进行的说明:: ...
- Laravel之路由 Route::get/post/any、路由参数、过滤器、命名、子域名、前缀、与模型绑定、抛出 404 错误、控制器
基本路由 应用中的大多数路都会定义在 app/routes.php 文件中.最简单的Laravel路由由URI和闭包回调函数组成. 基本 GET 路由 代码如下: Route::get('/', fu ...
- loadrunner基础学习笔记二
virtual user generator(vugen) 在测试环境中,loadrunner在物理计算机上使用vuser代替实际用户.vuser以一种可重复.可预测的方式模拟典型用户的操作,对系统施 ...
- python之tkinter使用-文件系统遍历
# tkinter:文件系统遍历 import tkinter as tk, os from time import sleep class DirList(object): def __init__ ...
- VS2017+WIN10自动生成类、接口的说明(修改类模板的方法)
微软发布VS2017的时候,我第一时间离线一份专业版,安装到了自己的电脑上,开始体验,但是问题来了,在开发中建立类和接口的时候,说 明注释总要自己写一次,烦!~~于是还是像以前一样改IDE默认的类和接 ...
- The Chinese Postman Problem HIT - 2739(有向图中国邮路问题)
无向图的问题,如果每个点的度数为偶数,则就是欧拉回路,而对于一个点只有两种情况,奇数和偶数,那么就把都为奇数的一对点 连一条 边权为原图中这两点最短路的值 的边 是不是就好了 无向图中国邮路问 ...
- ACM-ICPC国际大学生程序设计竞赛北京赛区(2017)网络赛 i题 Minimum(线段树)
描述 You are given a list of integers a0, a1, …, a2^k-1. You need to support two types of queries: 1. ...
- mysql 免安装版 启动服务马上关闭
在my.ini 加入这一句 1.直接在后面加上一下的参数 [mysqld] port=3306 basedir=D:\mysql-5.7.17-win32 datadir=D:\mysql-5.7.1 ...
- 【总结】 Lucas定理
\(Lucas\)定理: \(C^x_y≡C^{x/p}_{y/p}*C^{x\%p}_{y\%p} ~~(mod~p)\) 证明不会2333 void pre(){ A[0]=A[1]=B[0]=B ...
- Elasticsearch中使用groovy脚本处理boolean字段的一个问题
Elasticsearch中使用groovy脚本获取文档的bool字段值时,得到的值是字符的 'T' 或者 'F' ,而不是bool值 true 和 false . 比如文档中有一个字段是 { &qu ...