spring - Spring Boot 中的 I18n + Thymeleaf

标签 spring spring-boot internationalization thymeleaf

我正在尝试使用 Spring boot 和 Thymeleaf 制作多语言应用程序。

我制作了几个属性文件来保存不同的消息,但我只能用我的浏览器语言显示它(我尝试了扩展来更改浏览器区域设置,但它们似乎不起作用),无论如何我想放一个按钮在我的网站上执行此任务(更改语言),但我不知道如何或在哪里可以找到如何管理此任务。

给你看我的配置:

项目结构

Structure of the project


I18n 配置类

import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@EnableWebMvc
public class I18nConfiguration extends WebMvcConfigurerAdapter {

    @Bean
    public MessageSource messageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename("i18n/messages");
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }

}

Thymleaf HTML 页面

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
    th:with="lang=${#locale.language}" th:lang="${lang}">

<head>
<title>Spring Boot and Thymeleaf example</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <h3>Spring Boot and Thymeleaf</h3>
    <p>Hello World!</p>
    <p th:text="${nombre}"></p>
    <h1 th:text="#{hello.world}">FooBar</h1>
</body>
</html>

消息(属性文件)

messages_en_US.properties

hello.world = Hello people

messages_es.properties

hello.world = Hola gente

实际上消息是用西类牙语显示的,不知道我该如何更改,所以如果你能帮助我,非常感谢。

我想到了另一个问题...如何从数据库而不是属性文件中获取消息?

最佳答案

您的应用程序应该扩展 WebMvcConfigurerAdapter

@SpringBootApplication
public class NerveNetApplication extends WebMvcConfigurerAdapter {

    public static void main(String[] args) {
        SpringApplication.run(NerveNetApplication.class, args);
    }

    @Bean
    public LocaleResolver localeResolver() {
        return new CookieLocaleResolver();
    }

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

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

然后在浏览器上,您可以使用参数 lang 切换语言 示例:http://localhost:1111/?lang=kh其中messages_kh.properites 将存储高棉语的内容。

关于spring - Spring Boot 中的 I18n + Thymeleaf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36531131/

相关文章:

java - 重写抽象类的@bean方法以防止bean注入(inject)

Spring 测试上下文框架

java - 如何自定义 Spring Rest Controller 的 json 输出

java - 在 Spring Boot 应用程序中维护多个属性文件

java - 语言环境货币符号

java - 如何以编程方式实例化 Spring Boot 测试?

spring-boot - 如何使用 Spring Webflux 返回 GZIP 响应?

spring-boot - 未找到依赖项 : Spring Boot 的合格 bean 类型

javascript - 如何修复加载时在网页上显示翻译键的 Angular 翻译?

php - 如何在mysql中插入阿拉伯字母