【问题标题】:why is my internationalization not working (Spring Boot Application)为什么我的国际化不起作用(Spring Boot 应用程序)
【发布时间】:2023-01-14 05:06:55
【问题描述】:

这就是我向 Spring 应用程序添加国际化的方式。

首先,我在课堂上添加了:

@Configuration
public class SpringSecurityConfig {
    // ...
}

方法(这里我设置默认语言 - 波兰语):

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

接下来,在实现WebMvcConfigurer接口的类中,我添加了如下两个方法:

@Component
public class WebMvcConfigurerImpl implements WebMvcConfigurer {

    // ...

    // Configuring a component that supports changing language settings
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
        lci.setParamName("lang");
        return lci;
    }


    // Registering a component that supports changing the language
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localeChangeInterceptor());
    }

}

添加上面的代码后,我在resources文件夹中创建了两个文件labels.propertieslabels_en.properties。 在这些文件中,我会将 key=value 格式写入将显示在页面上的文本(我使用 Thymeleaf)。

接下来,我们需要在应用程序中注册这些文件,为此,在application.properties 文件中,我将名称标签添加到spring.messages.basename,如下所示:

spring.messages.basename=errors-messages,labels

现在,当请求中的页面收到 ...?lang=en(lang 参数的值为en)时,页面上的标签应该已经更改,但实际上并没有。

我做错了什么?

【问题讨论】:

    标签: java spring spring-boot thymeleaf


    【解决方案1】:

    你只需要稍微修改你的代码。不要使用some_url?lang=en,而是使用some_url?lang=en_GB

    例如,您可以拥有一个链接,该链接会触发语言更改为英语

     <a  id="link_en_GB" href="/some_url?lang=en_GB" >English</a>
    

    也就是说,我已经看到一些像您一样使用代码的示例 (..?lang=en),所以也许该代码在旧版本的 Spring 中是可以的。

    【讨论】:

      猜你喜欢
      • 2014-02-15
      • 1970-01-01
      • 1970-01-01
      • 2015-11-15
      • 2016-02-23
      • 1970-01-01
      • 2016-05-24
      • 2018-07-19
      • 1970-01-01
      相关资源
      最近更新 更多