I18n在Spring boot + Thymeleaf

No *_*One 12 spring internationalization thymeleaf spring-boot

我正在尝试使用Spring启动和Thymeleaf创建一个多语言应用程序.

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

要告诉你我的配置:

项目结构

项目结构


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;
    }

}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

消息(属性文件)

messages_en_US.properties

hello.world = Hello people
Run Code Online (Sandbox Code Playgroud)

messages_es.properties

hello.world = Hola gente
Run Code Online (Sandbox Code Playgroud)

实际上这条消息是用西班牙语显示的,不知道我怎么改变这个,所以如果你能帮助我,非常感谢你.

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

Lay*_*ros 14

您的应用程序应扩展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());
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在浏览器上你可以用param lang切换语言 例如:http:// localhost:1111 /?lang = kh messages_kh.properites将存储高棉语的内容.

  • 作为一个有点旧的答案,“WebMvcConfigurerAdapter”现在已被弃用。相反,您应该使用“implements WebMvcConfigurer”。此答案中的代码仍然按原样工作,接口替换了抽象类。 (4认同)