【问题标题】:Java Spring Internationalization (i18n) problemJava Spring 国际化(i18n)问题
【发布时间】:2019-02-18 15:42:27
【问题描述】:

我正在尝试学习使用 Java Spring 开发多语言网站。 看了一些教程后,我明白了它是如何工作的。 但我似乎犯了一些错误。

项目结构:

src
   └─── ???? main
       ├─── ???? java
       │   └─── ???? com
       │       └─── ???? example_project
       │           └─── ???? config
       │               └─── WebMvcConfig
       └─── ???? resources
           ├─── ???? i18n
           │   ├─── messages_en.properties
           │   └─── messages_fr.properties
           ├─── ???? static
           └─── ???? templates

WebMvcConfig.java

@EnableWebMvc
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

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

    @Bean
    public LocaleResolver localeResolver() {
        CookieLocaleResolver resolver = new CookieLocaleResolver();
        resolver.setDefaultLocale(new Locale("en"));
        resolver.setCookieName("lang_cookie");
        return resolver;
    }

    @Override
    public void addInterceptors(InterceptorRegistry reg) {
        LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();
        interceptor.setParamName("lang");
        reg.addInterceptor(interceptor);
    }
}

LandingController.java

@Controller
public class LandingController {

    @Layout("layout/default")
    @GetMapping("/")
    public String index() { return "index"; }

}

index.html

<div th:fragment="content">
    <ul>
        <li><a th:href="@{/?lang=en}"><img src="/assets/images/en.png"></a></li>
        <li><a th:href="@{/?lang=fr}"><img src="/assets/images/fr.png"></a></li>
    </ul>
    <p th:text="#{hello}"></p>
</div>

它只加载“en”属性文件,当我点击“fr”链接时,它会重新加载但不加载“fr”属性文件。

我不明白问题出在哪里。

【问题讨论】:

  • 什么问题出在哪里?
  • 它只加载 en 属性文件,当我点击 fr 链接时它重新加载但不加载 fr 属性文件。
  • 你怎么知道,什么时候你的页面上没有文字?
  • 我忘了在这里添加,我现在去编辑

标签: java spring spring-mvc internationalization thymeleaf


【解决方案1】:

您的 MessageSource 无法在两个属性文件中找到键为“hello”的消息。如果消息源无法在 fr 属性中找到该消息,它将返回 en 中的那个。 请确保您在两个文件中都定义了消息

  • messages_en.properties

hello=你好在 en

  • messages_fr.properties

hello=你好在 fr

【讨论】:

  • 感谢您的回答,我已经有了这两个具有相同密钥的属性文件,但是当我单击 url ?lang=fr 时,网站正在刷新,但它没有加载 fr 属性文件