如何使用 thymeleaf 和 spring 国际化动态更改语言 select link

How to change the language select link dinamically using thymeleaf and spring internacionalization

我正在开发一个必须具有国际化的网站,我正在尝试更改语言 Select 文本以使其根据用户现在使用的语言动态呈现。

假设该网站现在是葡萄牙语,那么语言 Select 文本应显示为 'English',值应相应更改,反之亦然。

现在的代码:

<select class="form-control dropdown2 col-lg-2 col-10 text-white" id="locales">
      <option>Idioma/Language</option>
      <option value="en" th:text="#{langEN}"></option>
      <option value="pt_BR" th:text="#{langPT}"></option>
</select>

$(document).ready(function() {
    $("#locales").change(function() {
        var selectedOption = $('#locales').val();
        if (selectedOption != '') {
            window.location.replace('?lang=' + selectedOption);
        }
        if(document.getElementById("clientPage")){
            window.location.replace(window.location.href + '&lang=' + selectedOption);
        }
    });
});

这是我正在努力实现的一个例子:

<a th:href="#{langURL}" th:text="#{lang}"></a>

其中 langURLlang 将在每种语言中设置为 message.properties。

编辑:

我的问题已使用以下代码解决:

<a th:href="@{/?lang=}+#{lang.url}" th:text=#{lang.text}></a>

我不确定您是否已经创建了实现此目的应该创建的所有 Bean,因此我将提供尽可能多的帮助,以便有人可以从头开始配置 Spring + Thymeleaf。

首先设置 localResolver bean 并设置默认语言环境:

@Bean
public LocaleResolver localeResolver() {
    SessionLocaleResolver slr = new SessionLocaleResolver();
    slr.setDefaultLocale(Locale.ENGLISH);
    return slr;
}

然后,在您的@Configuration class(应该实现 WebMvcConfigurer 接口)中设置 localeChangeInterceptor,以便它根据每个请求的 lang 参数更改语言:

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

并在应用程序的拦截器注册表中设置拦截器:

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

这就是 Spring 配置的全部内容。现在您需要将 messages.properties 个文件添加到您的 src/main/resources 文件夹中。使用以下格式在 messages.properties 文件名中设置语言:messages_??.properties,其中 ??是语言代码,例如:messages_en.properties 或 messages_fr.properties.

另请注意,如果语言代码(lang 参数)不作为现有语言环境存在,则应用程序将回退到默认语言环境。值。

最后,确保您的网址包含参数 lang=<language>,即 http://example.com/page?lang=fr