首页 > 编程语言 > 详细

21. SpringBoot 实现国际化 [i18n]

时间:2021-08-11 09:18:54      阅读:39      评论:0      收藏:0      [点我收藏+]

如果我们在SoringMVC 写国际化 ,那么肯定是 编写国际化配置文件 然后 使用ResourceBundleMessageSource管理国际化资源文件 ,在JSP页面使用fmt:message取出国际化内容.

技术分享图片

 

 

 我们的目标是把上面国际化

现在用SpringBoot写,我们先写 国际化配置文件properties ,,,SpringBoot 很方便写:

在response文件夹下新建 i18n,我们在里面写吧,新建3个文件:  【记住!!! properties编码要改变!  不然前功尽弃!】

技术分享图片

 

 

我们第一个做为默认  第二个 是en_US  美国 表示英语  ,第三个 zh_CN 表示中国。   【这里login 和 国家区域代码  是用  _  分开的。 】

当SpringBoot 会自动识别出 国家区域代码 然后可以很方便的 Add 添加。

技术分享图片

 

 

 

点击 Resoucre Bundle 可以快速编辑   这里自己来吧! 

技术分享图片

 

 

 

编辑好之后 即可。



 

SpringBoot 自动配置好了管理国际化资源文件的组件,我们查找看下主要源码 然后才知道怎么配置:

搜一下 MessageSourceAutoConfiguration 自动配置文件  可以看到里面配置:

主要配置1: MessageSourceAutoConfiguration 自动配置中特性:

/**
* 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.
*  这个注释说的是 如果你要使用你自己的国际化配置文件properties,那么你就得在配置文件中设置,如果没设置任何指定【指定的时候注意基础名】,
* 那么他就自动在resouce中寻找!
*/ public class MessageSourceAutoConfiguration { private static final Resource[] NO_RESOURCES = new Resource[0]; private String basename = "messages";    //我们的配置文件可以直接放在类路径下叫messages.properties,他会自动读取。
////主要配置2 :添加了个组件进入,其中这里设置的是 基础名,结合上面 一起配置国际化功能
@Bean
    public MessageSource messageSource() {
        //全称
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        if (StringUtils.hasText(this.basename)) {
            //这里是设置国际化文件的基础名(就是_和国家区域代码分开的前一个 比如我们的 login_zh_CN 基础名就是login) 他这里默认就是message了,所以他会自动去找message....
            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;
    }

 

所以我们现在去 配置文件中 配置下 基础名:

技术分享图片

 

 



 

最后在HTML 直接用Thynelemaf模板代码 #{...}:进行获取国际化内容:(确保你配置了Thymeleaf!和 properties的编码 不然出现乱码!) 如果都配置了 还是乱码,那么你看你html文件缺少默认编码头meta (<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>)没。

 

 

 

 

 

21. SpringBoot 实现国际化 [i18n]

原文:https://www.cnblogs.com/bi-hu/p/15126230.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!