java - 无法访问区域设置消息

标签 java spring-boot thymeleaf

我在资源目录中定义了两个属性文件。 他们是:- messages_es_ES.properties

message.welcome=Se registro correctamente. Le enviaremos

messages_en.properties

message.welcome=Welcome To our main login page

现在我尝试使用 thymeleaf 在我的 html 页面上访问此消息,如下所示:-

<h1 th:text="#{message.welcome}"></h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. 
  Obcaecati voluptatibus odio vero et quasi, incidunt quae eaque 
  maiores repellendus totam placeat autem quam eligendi ut in 
  veritatis. Dolores, repellendus dolor.</p>

和我的配置文件:-

@Configuration
public class MvcConfig implements WebMvcConfigurer {

    @Autowired
    private MessageSource messageSource;


    public MvcConfig() {
        super();
    }


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


    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor(){
        LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
        lci.setParamName("lang");
        return lci;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localeChangeInterceptor());
    }

    @Override
    public Validator getValidator() {
        LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
        validator.setValidationMessageSource(messageSource);
        return validator;
    }

}

enter image description here enter image description here

为什么不显示欢迎消息?

最佳答案

从您的代码结构来看,您似乎将 messages 移动到子目录:/messages/messages_en.properties 因此默认的 messageSource 会这样做没看到。

您需要覆盖默认的messageSource:

@Bean
@Primary // Must use this to override message source
public static MessageSource messageSource() {
    ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
    messageSource.setBasenames("classpath:messages/messages");
    messageSource.setDefaultEncoding(StandardCharsets.UTF_8.name());
    messageSource.setFallbackToSystemLocale(true);
    return messageSource;
 }

将其放入您的 MvcConfig

关于java - 无法访问区域设置消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50539178/

相关文章:

java - 尝试使用 JavaFX 导入 mp3 文件时出错

java - 更改 MultiKeyMap 的每个值 (Apache Commons)

java - 我是唯一一个 IDEA 的自动导入在 Kotlin 中不起作用的人吗?

java - 2 个配置文件,2 个方法实现,1 个通过 Thymeleaf 调用 html 文件。如何?

json - 修改来自 Spring Boot Rest Controller 的默认 JSON 错误响应

java - 如果字符串包含 thymeleaf 中的键,如何设置字符串中的值

java - 使用 Clear 解析器进行语义角色标记

Spring Boot OAuth2 - 无法从 token 获取用户详细信息

java - 在 Spring 4 中定义异常处理程序以返回自定义 404 和 500 页面

spring - 如何将 css 和 js 添加到 Spring Boot 应用程序中?