【问题标题】:Spring MVC + Thymeleaf i18n acting differently on different machinesSpring MVC + Thymeleaf i18n 在不同机器上的作用不同
【发布时间】:2020-09-15 14:02:48
【问题描述】:

我在我的应用程序中启用了 i18n,它需要 2 种不同的语言版本,用户可以随时输入其中的任何一种。 按照说明,我实施了以下方法:

    @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());
    }

通过将“?lang=ru”或“?lang=en”附加到 url 并重新加载页面来切换区域设置。消息存储在 messages.properties 和 messages_ru.properties 中。

问题是它在我的机器上完美运行(在 MacOS、tomcat 9.0.36 和 openjdk 12 上运行)但是当我将它部署到生产服务器时(Windows Server 2008 R2、tomcat 8.5 或 9.0.37 - 结果相同) 它只是不会更改语言环境更改时显示的文本。

我也尝试过使用带有 defaultLocale 设置的 SessionLocaleResolver,但这并没有改变。有人可以帮帮我吗?

编辑:我使用Thymleaf 作为模板处理器。此外,此服务器是nginx 后面的安全 (https) 公司服务器。但即使我在服务器本身打开应用程序,它仍然存在。

编辑 2:经过进一步的实验,我注意到这可能是 thymeleaf 错误:当我使用 LocaleContextHolder 中的 Locale 时,它​​会正确返回当前语言环境。只有Thymeleaf 仍然显示错误消息来源。

【问题讨论】:

    标签: java spring internationalization thymeleaf


    【解决方案1】:

    解决了。 MessageSource 似乎需要对位置进行显式属性文件命名 - 所以我在基本消息文件中添加了“_en”。我也像这样手动声明了 MessageSource bean:

        @Bean
        public MessageSource messageSource() {
            ResourceBundleMessageSource rbms = new ResourceBundleMessageSource();
            rbms.setBasename( "messages" );
            rbms.setDefaultEncoding( "UTF-8" );
            rbms.setFallbackToSystemLocale( false );
            return rbms;
        }
    

    并使用了 SessionLocaleResolver。

    【讨论】:

    • 这很奇怪。回退到 messages.properties 应该可以正常开箱即用。
    • 是的,这让我很头疼,因为这在我的开发机器上运行良好,在部署时无法运行。仍然无法弄清楚它不起作用的原因。此外,我已经完全删除了默认的 messages.properties,只留下了特定于语言的文件,并且可以在任何地方使用。
    猜你喜欢
    • 1970-01-01
    • 2017-04-20
    • 2015-05-23
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 2020-10-15
    • 2014-09-09
    • 2016-05-06
    相关资源
    最近更新 更多