Как настроить интернационализацию с помощью Spring Boot + Thymeleaf? - PullRequest
0 голосов
/ 19 мая 2018

В проекте Spring Boot, использующем Thymeleaf в качестве средства визуализации шаблонов, как можно продолжить перевод фрагмента текста на несколько языков в зависимости от языкового стандарта пользователя?

Как отобразить эти сообщения вThymeleaf

1 Ответ

0 голосов
/ 19 мая 2018

Например, Spring Boot 2.0.2.RELEASE

Файл WebConfig.java

// File /src/main/java/com/donhuvy/WebConfig.java
package com.donhuvy;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import java.util.Locale;

/**
 * Configuration for overall application.
 */
//@EnableWebMvc
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class WebConfig extends WebMvcConfigurationSupport {

    /**
     * Switch language, default language is Vietnamese - Vy's mother tongue language.
     * If user would like to switch to other language, use parameter,
     * for example: http://localhost:8081/all?lang=en
     *
     * @return
     */
    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
        // sessionLocaleResolver.setDefaultLocale(Locale.US);
        Locale vietnamLocale = new Locale("vi", "VN");
        sessionLocaleResolver.setDefaultLocale(vietnamLocale);
        return sessionLocaleResolver;
    }

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
        lci.setParamName("lang");
        return lci;
    }

    @Override
    public void addInterceptors(InterceptorRegistry ir) {
        ir.addInterceptor(localeChangeInterceptor());
    }

}

Нужно 3 файла *.properties

Файл messages.properties

cash.list.currency_code=Currency code
cash.list.description=Description
cash.list.order_number=No.
cash.receipt.object.name=Object name
cash.list.conversion_rate=Conversion rate

Файл messages_en.properties

cash.list.currency_code=Currency code
cash.list.description=Description
cash.list.order_number=No.
cash.receipt.object.name=Object name
cash.list.conversion_rate=Conversion rate

Файл messages_vi.properties

cash.list.currency_code=Mã tiền tệ
cash.list.description=Mô tả
cash.list.order_number=STT
cash.receipt.object.name=Đối tượng
cash.list.conversion_rate=Tỷ giá

Просмотр файла ccy.html

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">

<!-- File: /src/main/resources/templates/cash/ccy.html -->

<!--<th:block th:include="fragments/header :: header"></th:block>-->
<!--For suggest css class purpose-->
<!--<link rel="stylesheet" href="../../static/bootstrap.min.css">-->
<th:block th:include="fragments/header"></th:block>

<div class="row">
    <div class="col-lg-12 col-md-12">
        <table class="table table-bordered table-striped">
            <thead class="thead-light">
            <tr>
                <th><span th:text="#{cash.list.order_number}"></span></th>
                <th><span th:text="#{cash.list.currency_code}"/></th>
                <th><span th:text="#{cash.list.description}"></span></th>
                <th><span th:text="#{cash.list.conversion_rate}"/></th>
            </tr>
            </thead>
            <tbody>
            <tr th:each="currency : ${currencies}">
                <!--/*@thymesVar id="currency" type="com.donhuvy.entity.Ccy"*/-->
                <td><span th:text="${currency.currencyId}"/></td>
                <td><span th:text="${currency.currencyName}"/></td>
                <td><span th:text="${currency.ccyName}"/><td>
                <span th:text="${currency.convertRate}"/></td>
            </tr>
            </tbody>
        </table>
    </div>
</div>

<!--<th:block th:include="fragments/footer :: footer"></th:block>-->
<th:block th:include="fragments/footer"></th:block>

Посмотреть результатна определенном языке:

http://localhost:8081/all (язык по умолчанию)

http://localhost:8081/all?lang=en

http://localhost:8081/all?lang=vi

Ссылка: https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#using-thtext-and-externalizing-text

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...