简体   繁体   English

Java Spring国际化(i18n)问题

[英]Java Spring Internationalization (i18n) problem

Im trying to learn developing multilingual websites with Java Spring. 我试图学习使用Java Spring开发多语言网站。 After watching a few tutorials i understood how it works. 看完一些教程后,我了解了它的工作原理。 But it seems that im making some mistakes. 但是,看来我在犯一些错误。

Project structure: 项目结构:

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

WebMvcConfig.java 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 LandingController.java

@Controller
public class LandingController {

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

}

index.html 的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>

Its loading only "en" properties file, when im clicking to "fr" link its reloading but not loading the "fr" properties file. 其仅加载“ en”属性文件,当我单击“ fr”时,链接其重新加载但不加载“ fr”属性文件。

I cant understand where is the problem. 我不明白问题出在哪里。

Your MessageSource is not able to find the message with key "hello" in both properties files. 您的MessageSource在两个属性文件中都找不到键为“ hello”的消息。 If the message source is not able to find the message in fr properties, it will return the one from en. 如果消息源无法在fr属性中找到消息,它将从en中返回消息。 Please make sure that you defined the message in both files 请确保您在两个文件中都定义了消息

  • messages_en.properties messages_en.properties

hello=Hello in en hello =你好

  • messages_fr.properties messages_fr.properties

hello=Hello in fr 你好=你好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM