实战SpringBoot 快速支持动态配置国际化

admin 2022年3月30日11:50:17评论878 views1字数 5814阅读19分22秒阅读模式

大家好,我是冰河~~

最近有很多小伙伴问我如何在SpringBoot中快速配置国际化,说白了,就是支持多语言,并且需要支持动态切换语言。好吧,我弄了个实战demo,分享给大家吧。

点击上方卡片关注我

线上项目结构吧,看图:

实战SpringBoot 快速支持动态配置国际化

后台国际化

配置国际化参数

默认解析器:LocaleResolver  用于设置当前会话的默认的国际化语言。

默认拦截器:LocaleChangeInterceptor  指定切换国际化语言的参数名。例如?lang=zh_CN 表示读取国际化文件messages_zh_CN.properties

/**
 * 配置国际化语言
 */

@Configuration
public class LocaleConfig {

    /**
     * 默认解析器 其中locale表示默认语言
     */

    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver localeResolver = new SessionLocaleResolver();
        localeResolver.setDefaultLocale(Locale.US);
        return localeResolver;
    }

    /**
     * 默认拦截器 其中lang表示切换语言的参数名
     */

    @Bean
    public WebMvcConfigurer localeInterceptor() {
        return new WebMvcConfigurer() {
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                LocaleChangeInterceptor localeInterceptor = new LocaleChangeInterceptor();
                localeInterceptor.setParamName("lang");
                registry.addInterceptor(localeInterceptor);
            }
        };
    }
}

添加国际化文件

首先在配置文件 application.yml 填写国际化文件的相对路径,表示读取classpath:/static/i18n/messages_language_country.properties 。例如:

spring:
  messages:
    basename: static/i18n/messages #相对路径 开头请勿添加斜杠

然后在 classpath:/static/i18n 目录中添加如下国际化文件:

默认文件:messages.properties

#这里填写默认翻译,内容可以留空,但文件必须存在。

美式英语:messages_en_US.properties

#这里填写英语翻译。
user.title=User Login
user.welcome=Welcome
user.username=Username
user.password=Password
user.login=Sign In

中文简体:messages_zh_CN.properties

#这里填写中文翻译
user.title=用户登陆
user.welcome=欢迎
user.username=登陆用户
user.password=登陆密码
user.login=登陆

中文繁体:messages_zh_TW.properties

#这里填写繁体翻译
user.title=用戶登陸
user.welcome=歡迎
user.username=登陸用戶
user.password=登陸密碼
user.login=登陸

代码国际化

通过工具类的静态方法MessageUtils.get("user.title") 快速获取当前国际化的翻译值。

/**
 * 国际化工具类
 */

@Component
public class MessageUtils{

    private static MessageSource messageSource;

    public MessageUtils(MessageSource messageSource) {
        FastLocale.messageSource = messageSource;
    }

    /**
     * 获取单个国际化翻译值
     */

    public static String get(String msgKey) {
        try {
            return messageSource.getMessage(msgKey, null, LocaleContextHolder.getLocale());
        } catch (Exception e) {
            return msgKey;
        }
    }
}

页面国际化

首先在pom文件引入ThymeleafWeb依赖,然后在页面中只需通过th:xx="#{x.label}"即可获取对应的国际化翻译值。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

例如:

<title th:text="#{user.title}">用户登陆</title>

JS国际化

首先在pom文件引入jQueryjquery-properties-i18n等依赖,然后在初始化后即可通过JS函数获取对应国际化文件的内容。

<dependency><!--webjars版本定位器 用于省略版本号-->
    <groupId>org.webjars</groupId>
    <artifactId>webjars-locator-core</artifactId>
</dependency>

<dependency><!--jQuery前端依赖-->
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>3.3.1</version>
</dependency>

<dependency><!--jQuery国际化插件-->
    <groupId>org.webjars.bower</groupId>
    <artifactId>jquery-i18n-properties</artifactId>
    <version>1.2.7</version>
</dependency>

例如:为了提高可用性 这里提供了获取当前国际化语言和获取国际化翻译的方法。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <head>
        <title th:text="#{user.title}">用户登陆</title>
        <script th:src="@{/webjars/jquery/jquery.min.js}"></script>
        <script th:src="@{/webjars/jquery-i18n-properties/jquery.i18n.properties.min.js}"></script>

        <script th:inline="javascript">
            //获取应用路径
            var ROOT = [[${#servletContext.contextPath}]];

            //获取默认语言
            var LANG_COUNTRY = [[${#locale.language+'_'+#locale.country}]];

            //初始化i18n插件
            $.i18n.properties({
                path: ROOT + '/i18n/',//这里表示访问路径
                name: 'messages',//文件名开头
                language: LANG_COUNTRY,//文件名语言 例如en_US
                mode: 'both'//默认值
            });

            //初始化i18n函数
            function i18n(msgKey) {
                try {
                    return $.i18n.prop(msgKey);
                } catch (e) {
                    return msgKey;
                }
            }

            //获取国际化翻译值
            console.log(i18n('user.title'));
            console.log(i18n('User Login'));
        </script>
    </head>
    <body>
    <div class="logo_box">
        <select id="locale">
            <option value="zh_CN">中文简体</option>
            <option value="zh_TW">中文繁体</option>
            <option value="en_US">English</option>
        </select>
        <h3 th:text="#{user.welcome}">欢迎登陆</h3>

        <form>
            <div class="input_outer">
                <span class="u_user"></span>
                <input id="username" name="username" class="text" type="text" th:placeholder="#{user.username}">
            </div>
            <div class="input_outer">
                <span class="us_uer"></span>
                <input id="password" name="password" class="text" type="password" th:placeholder="#{user.password}">
            </div>
            <div class="mb2">
                <a class="act-but submit" th:text="#{user.login}">登录</a>
            </div>
        </form>
    </div>


    <script th:inline="javascript">
        //选中语言
        $("#locale").find('option[value="' + LANG_COUNTRY + '"]').attr('selected'true);

        //切换语言
        $("#locale").change(function ({
            $.get(ROOT + '/?lang=' + $("#locale").val(), function () {
                location.reload();
            });
        });

    
</script>
    </body>
</html>

关于i18n插件的更多配置项请查阅 jquery-properties-i18n 官方文档。

语言切换

很多新人配置好之后不懂得如何切换国际化语言,其实很简单,由于在前面已经配置了拦截器LocaleChangeInterceptor ,此时我们只需在任意请求中附上语言参数lang即可,当然也通过AJAX来快速切换。

例如:

  • 默认英语:http://http://127.0.0.1:8080?lang=en_US
  • 中文简体:http://http://127.0.0.1:8080?lang=zh_CN
  • 中文繁体:http://http://127.0.0.1:8080?lang=zh_TW

工程演示

英文界面

实战SpringBoot 快速支持动态配置国际化

中文界面

实战SpringBoot 快速支持动态配置国际化

好了,今天就到这儿吧,我是冰河,我们下期见~~

转自:jianshu.com/p/e2eae08f3255

点击上方卡片关注我

原文始发于微信公众号(冰河技术):实战SpringBoot 快速支持动态配置国际化

免责声明:文章中涉及的程序(方法)可能带有攻击性,仅供安全研究与教学之用,读者将其信息做其他用途,由读者承担全部法律及连带责任,本站不承担任何法律及连带责任;如有问题可邮件联系(建议使用企业邮箱或有效邮箱,避免邮件被拦截,联系方式见首页),望知悉。
  • 左青龙
  • 微信扫一扫
  • weinxin
  • 右白虎
  • 微信扫一扫
  • weinxin
admin
  • 本文由 发表于 2022年3月30日11:50:17
  • 转载请保留本文链接(CN-SEC中文网:感谢原作者辛苦付出):
                   实战SpringBoot 快速支持动态配置国际化https://cn-sec.com/archives/854807.html
                  免责声明:文章中涉及的程序(方法)可能带有攻击性,仅供安全研究与教学之用,读者将其信息做其他用途,由读者承担全部法律及连带责任,本站不承担任何法律及连带责任;如有问题可邮件联系(建议使用企业邮箱或有效邮箱,避免邮件被拦截,联系方式见首页),望知悉.

发表评论

匿名网友 填写信息