在使用Thymeleaf作为模板渲染器的Spring Boot项目中,如何根据用户区域设置将一段文本翻译成多种语言?
如何在Thymeleaf中显示这些消息?
答案 0 :(得分:1)
例如,Spring Boot 2.0.2.RELEASE
档案AmazonCloudSearchDomainException: null (Service: AmazonCloudSearchDomain; Status Code: 411; Error Code: null...
WebConfig.java
需要3个文件// 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());
}
}
档案*.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
以特定语言查看结果:
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