微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 Spring 中使用 thymeleaf 在外化消息之间切换?

如何解决如何在 Spring 中使用 thymeleaf 在外化消息之间切换?

春天 + 百里香

我想根据需要显示来自 Messages_pl.propertiesMessages_en.properties 的消息。这是我的问题,因为当我想查看第二个文件中的消息时我不知道该怎么做(认情况下会考虑 Messages_pl.properties)。

为了使用指定的基名访问资源包,我将下面的 bean 添加到我的 @Configuration 类中:

@Bean
    public ResourceBundleMessageSource messageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename("Messages");
        return messageSource;
    }

Messages_pl.properties

welcome.message=siemanko

Messages_en.properties

welcome.message=hello

我使用此属性的 html 文件片段:

 <h1 th:text="#{message.welcome}"></h1>

结果:siemanko

我应该怎么做才能得到 hello 的结果?

解决方法

您可以在同一文件 Messages.properties 上定义以下内容:

welcome.message.pl=siemanko
welcome.message.en=hello

然后您可以使用本地解析器使您的项目能够确定当前正在使用的区域设置:

@Bean
public LocaleResolver localeResolver() {
    return new CookieLocaleResolver();
}

然后添加一个你的语言的拦截器:

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

之后在语言之间切换很简单,您只需要更改链接上参数 lang 的值:

localhost:8080/your_page?lang=pl // will show siemanko on your page
localhost:8080/your_page?lang=en // will show hello on your page

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。