SpringBoot - 资源国际化

2018年06月19日 11:00:31 流烟默 阅读数:344

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/J080624/article/details/80730674

【1】SpringBoot的自动配置

SpringBoot自动配置好了管理国际化资源文件的组件:

@Configuration
@ConditionalOnMissingBean(value = MessageSource.class, search = SearchStrategy.CURRENT)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@Conditional(ResourceBundleCondition.class)
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "spring.messages")
public class MessageSourceAutoConfiguration {private static final Resource[] NO_RESOURCES = {};/*** Comma-separated list of basenames (essentially a fully-qualified classpath* location), each following the ResourceBundle convention with relaxed support for* slash based locations. If it doesn't contain a package qualifier (such as* "org.mypackage"), it will be resolved from the classpath root.*/private String basename = "messages";//我们的配置文件可以直接放在类路径下叫messages.properties;/*** Message bundles encoding.*/private Charset encoding = Charset.forName("UTF-8");/*** Loaded resource bundle files cache expiration, in seconds. When set to -1, bundles* are cached forever.*/private int cacheSeconds = -1;/*** Set whether to fall back to the system Locale if no files for a specific Locale* have been found. if this is turned off, the only fallback will be the default file* (e.g. "messages.properties" for basename "messages").*/private boolean fallbackToSystemLocale = true;/*** Set whether to always apply the MessageFormat rules, parsing even messages without* arguments.*/private boolean alwaysUseMessageFormat = false;//为容器添加了ResourceBundleMessageSource 组件@Beanpublic MessageSource messageSource() {ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();if (StringUtils.hasText(this.basename)) {//设置国际化资源文件的基础名(去掉语言国家代码的)messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(this.basename)));}if (this.encoding != null) {messageSource.setDefaultEncoding(this.encoding.name());}messageSource.setFallbackToSystemLocale(this.fallbackToSystemLocale);messageSource.setCacheSeconds(this.cacheSeconds);messageSource.setAlwaysUseMessageFormat(this.alwaysUseMessageFormat);return messageSource;}

还可以在SpringBoot的配置文件中使用spring.messages前缀配置国际化:

# 国际化配置文件(包名.基础名)
spring.messages.basename=i18n.login

【2】编写国际化资源文件

抽取页面需要显示的国际化消息,编写国际化资源文件。

login.properties

如图所示,idea会自动切换到国际化视图。另外,在编写properties时,除了传统的使用key:value在properties中编写外,还可以如下所示:


【3】页面示例

如下所示,在页面中使用properties的属性:


<label class="sr-only" th:text="#{login.username}">Username</label>
<input type="text"  name="username" class="form-control" placeholder="Username" th:placeholder="#{login.username}" required="" autofocus="">
<label class="sr-only" th:text="#{login.password}">Password</label>
<input type="password" name="password" class="form-control" placeholder="Password" th:placeholder="#{login.password}" required="">
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me"/> [[#{login.remember}]]
//这里使用行内写法,input是自结束标签,没有标签体
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.btn}">Sign in</button>

注意这里使用的是#{…}语法,可以参考Thymeleaf中第四章Standard Expression Syntax中4.1Messages讲解,如下图.

 


测试结果:

浏览器设置英文:


浏览器设置中文:


【4】SpringBoot对资源国际化解析原理

首先明白两个组件:国际化Locale(区域信息对象);LocaleResolver(获取区域信息对象)。

① WebMVCAutoConfiguration中对LocaleResolver 配置

@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "spring.mvc", name = "locale")
public LocaleResolver localeResolver() {if (this.mvcProperties.getLocaleResolver() == WebMvcProperties.LocaleResolver.FIXED) {return new FixedLocaleResolver(this.mvcProperties.getLocale());}AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();localeResolver.setDefaultLocale(this.mvcProperties.getLocale());return localeResolver;
}

如果spring.mvc.locale没有指定,那么就返回一个AcceptHeaderLocaleResolver 。如果指定了spring.mvc.locale,那么就返回FixedLocaleResolver。


② 查看AcceptHeaderLocaleResolver

@Overridepublic Locale resolveLocale(HttpServletRequest request) {Locale defaultLocale = getDefaultLocale();if (defaultLocale != null && request.getHeader("Accept-Language") == null) {return defaultLocale;}Locale requestLocale = request.getLocale();if (isSupportedLocale(requestLocale)) {return requestLocale;}Locale supportedLocale = findSupportedLocale(request);if (supportedLocale != null) {return supportedLocale;}return (defaultLocale != null ? defaultLocale : requestLocale);}

从请求头里面解析Locale!这也就是为什么浏览器切换语言显示不同资源的原理。


【5】中英切换

如下图所示,通过点击中文英文按钮切换不同资源显示:


① 页面修改如下:

<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>

这里使用的是Thymeleaf模板引擎中链接参数的写法(key=value),也可以使用原始写法如下:

<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>

② 编写自定义区域信息解析器

/*** 可以在连接上携带区域信息*/
public class MyLocaleResolver implements LocaleResolver {@Overridepublic 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;}@Overridepublic void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {}
}

将其添加到容器中:

@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {@Beanpublic LocaleResolver localeResolver(){return new MyLocaleResolver();}
}

③ Locale.getDefault()

该方法根据系统环境拿到Locale,如本机上如果没有传 l 参数,那么就会返回defaultLocale。此时无论浏览器语言设置什么,都显示中文。

 /*** Gets the current value of the default locale for this instance* of the Java Virtual Machine.* <p>* The Java Virtual Machine sets the default locale during startup* based on the host environment. It is used by many locale-sensitive* methods if no locale is explicitly specified.* It can be changed using the* {@link #setDefault(java.util.Locale) setDefault} method.** @return the default locale for this instance of the Java Virtual Machine*/public static Locale getDefault() {// do not synchronize this method - see 4071298return defaultLocale;}

SpringBoot - 资源国际化相关推荐

  1. SpringBoot项目国际化

    SpringBoot项目国际化 1. 创建国际化文件Resource Bundle 项目结构图: springboot项目工程详细结构 国际化文件结构图: springboot国际化文件 在Intel ...

  2. SpringBoot -> 国际化(i18n)

    文章目录 上结果 1.准备工作 配置文件编写 配置文件生效探究 配置页面国际化值 配置国际化解析 总结:我可能骗了你们,这个看了我都总结不出什么东西 上结果 1.准备工作 先在IDEA中统一设置pro ...

  3. java相关的国际化步骤_Java语言资源国际化步骤

    语言资源国际化步骤: ??1. 定义资源文件(如:language),需要使用命令native2ascii命令进行转码:(native2ascii是jdk中的转码工具,在jdk的bin目录下) ??2 ...

  4. SpringBoot 实现国际化 SpringBoot配置国际化 SpringBoot 国际化 springboot实现国际化 springboot配置国际化 springboot国际化代码实现

    SpringBoot 实现国际化,不使用 spring i18n实现方式 配置 全局语言地区拦截器配置 将拦截器注册 多语言实现 多语言接口 中文语言接口实现类 英文语言接口实现类 初始化 使用 配置 ...

  5. 自学SpringBoot之国际化配置相关的坑

    前两天在b站上自学SpringBoot的国际化配置时,浏览器总是报乱码的错,类似??login.tip_zh_CN??, 由于b站上基本都是使用Ideal,我用的是sts2.2.5版本,难免遇到不同, ...

  6. springboot配置国际化资源文件 使用themself模板进行解析

    2019独角兽企业重金招聘Python工程师标准>>> @ConfigurationProperties(prefix = "spring.messages") ...

  7. SpringBoot实现国际化

    在哔哩哔哩一位up主视频中学到的! 国际化 原理 通过Properties文件配置,配置完后通过Thymeleaf中的#{} 来取代原来的静态资源.例如: spring:# 关闭模板引擎的缓存thym ...

  8. Java中读取属性文件以及做资源国际化

    在src下的文件,没写包名 import java.text.MessageFormat; import java.util.Locale; import java.util.ResourceBund ...

  9. SpringBoot2.1.5(18)--- 国际化配置,SpringBoot Locale 国际化使用方法

    在项目中,很多时候需要国际化的支持,这篇文章要介绍一下springboot项目中多语言国际化的使用. 本文项目结构如图: springboot默认就支持国际化的,而且不需要你过多的做什么配置,只需要在 ...

最新文章

  1. NPOI读写Excel
  2. html5引入spring标签,[MVC]5 使用Spring标签库
  3. 【1863】畅通工程 (HDU)
  4. Oracle学习笔记之一,重温范式
  5. python常用时间处理方法
  6. JZOJ 2413. 【NOI2005】维护数列
  7. CSP前训练错误集锦
  8. python弹窗输入_Python中使用tkinter弹窗获取输入文本
  9. 单元格中指定内容标红_按照指定单元格内容进行拆分,想怎么拆就怎么拆
  10. ORACLE11g安装过程-windows
  11. [转载] boost python numpy_boost.python 与 boost.numpy安装的一些注意事项
  12. Asp.Net异步加载
  13. python通信系统仿真_详解MATLAB/Simulink通信系统建模与仿真 PDF 高清版
  14. endnote X7使用方法
  15. signature=44e925e612735a871c9c44002806d71b,英文书信格式
  16. 如何用电脑录制视频?图文教学,快速学会
  17. ArcGIS Runtime API for Android100.13.0加载TPK包、Runtime包、WMS地图服务、三维模式
  18. 计算机专业裁合词英语,计算机专业英语的构词方法
  19. hdu 1419 最大独立集
  20. iOS视频播放的基本方法

热门文章

  1. MFC1、动态创建CButton
  2. 集成测试用例_如何评估测试用例的有效性?
  3. 【飞控理论】四旋翼飞行器控制原理
  4. 数值计算方法(零)——运算的要求+基本算法
  5. 单目视觉里程计 mono vo
  6. mysql join 与 cross join 效率_浅析Mysql Join语法以及性能优化
  7. android input 点击事件失效,React Native:TextInput元素上的onContentSizeChange事件在Android上不起作用...
  8. Java之动手动脑(三)
  9. Spark学习之第一个程序打包、提交任务到集群
  10. html5--3.1 form元素