SpringBoot 快速支持國際化i18n

只需體驗(yàn)三分鐘 就會(huì)愛上這款國際化!

學(xué)習(xí)目標(biāo)

  • 快速學(xué)會(huì)如何在工程中支持國際化語言。

快速查閱

專題閱讀:《SpringBoot 布道系列》

源碼下載:springboot-locale-i18n

— Hey Man,Don't forget to Star or Fork . —

項(xiàng)目結(jié)構(gòu):

使用教程

一、后臺(tái)國際化

1、配置國際化參數(shù)

默認(rèn)解析器:LocaleResolver 用于設(shè)置當(dāng)前會(huì)話的默認(rèn)的國際化語言。

默認(rèn)攔截器:LocaleChangeInterceptor 指定切換國際化語言的參數(shù)名。例如?lang=zh_CN 表示讀取國際化文件messages_zh_CN.properties。

/**
 * 配置國際化語言
 */
@Configuration
public class LocaleConfig {

    /**
     * 默認(rèn)解析器 其中l(wèi)ocale表示默認(rèn)語言
     */
    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver localeResolver = new SessionLocaleResolver();
        localeResolver.setDefaultLocale(Locale.US);
        return localeResolver;
    }

    /**
     * 默認(rèn)攔截器 其中l(wèi)ang表示切換語言的參數(shù)名
     */
    @Bean
    public WebMvcConfigurer localeInterceptor() {
        return new WebMvcConfigurer() {
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                LocaleChangeInterceptor localeInterceptor = new LocaleChangeInterceptor();
                localeInterceptor.setParamName("lang");
                registry.addInterceptor(localeInterceptor);
            }
        };
    }
}

2、添加國際化文件

首先在配置文件 application.yml 填寫國際化文件的相對(duì)路徑,表示讀取classpath:/static/i18n/messages_language_country.properties 。例如:

spring:
  messages:
    basename: static/i18n/messages #相對(duì)路徑 開頭請(qǐng)勿添加斜杠

然后在 classpath:/static/i18n 目錄中添加如下國際化文件:

默認(rèn)文件:messages.properties

#這里填寫默認(rèn)翻譯,內(nèi)容可以留空,但文件必須存在。

美式英語: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=登陸

3、代碼國際化

通過工具類的靜態(tài)方法MessageUtils.get("user.title") 快速獲取當(dāng)前國際化的翻譯值。


/**
 * 國際化工具類
 */
@Component
public class MessageUtils{

    private static MessageSource messageSource;

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

    /**
     * 獲取單個(gè)國際化翻譯值
     */
    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}"即可獲取對(duì)應(yīng)的國際化翻譯值。

        <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文件引入jQuery、jquery-properties-i18n等依賴,然后在初始化后即可通過JS函數(shù)獲取對(duì)應(yīng)國際化文件的內(nèi)容。

        <dependency><!--webjars版本定位器 用于省略版本號(hào)-->
            <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>

例如:為了提高可用性 這里提供了獲取當(dāng)前國際化語言和獲取國際化翻譯的方法。

<!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">
        //獲取應(yīng)用路徑
        var ROOT = [[${#servletContext.contextPath}]];

        //獲取默認(rèn)語言
        var LANG_COUNTRY = [[${#locale.language+'_'+#locale.country}]];

        //初始化i18n插件
        $.i18n.properties({
            path: ROOT + '/i18n/',//這里表示訪問路徑
            name: 'messages',//文件名開頭
            language: LANG_COUNTRY,//文件名語言 例如en_US
            mode: 'both'//默認(rèn)值
        });

        //初始化i18n函數(shù)
        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>

關(guān)于i18n插件的更多配置項(xiàng)請(qǐng)查閱 jquery-properties-i18n 官方文檔

四、語言切換

很多新人配置好之后不懂得如何切換國際化語言,其實(shí)很簡單,由于在前面已經(jīng)配置了攔截器LocaleChangeInterceptor ,此時(shí)我們只需在任意請(qǐng)求中附上語言參數(shù)lang即可,當(dāng)然也通過AJAX來快速切換。

例如:
默認(rèn)英語: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

五、工程演示

英文界面

中文界面

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容