无法访问区域设置消息

时间:2018-05-26 03:54:03

标签: 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

现在我正在尝试使用这样的百万美元在我的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

为什么不显示欢迎信息?

1 个答案:

答案 0 :(得分:1)

从您的代码结构看,您将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班级