SpringBoot 快速支持國際化i18n


學習目標

  • 快速學會如何在工程中支持國際化語言。

快速查閱

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

源碼下載:springboot-locale-i18n

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

項目結構:

 

 

 

使用教程

一、后台國際化

1、配置國際化參數

默認解析器: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);
            }
        };
    }
}

2、添加國際化文件

首先在配置文件 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=登陸

 

3、代碼國際化

通過工具類的靜態方法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

五、工程演示

英文界面

 


 

中文界面

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM