带Sping Boot 和thymeleaf的Spring MVC 4-i18 n不工作

vcudknz3  于 2022-11-14  发布在  Spring
关注(0)|答案(2)|浏览(147)

我试图在springmvc 4中用 Boot 做一个简单的国际化示例,但是没有成功。

下面是我的java配置:

import java.util.Locale;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

@Configuration
public class WebConfiguration extends WebMvcConfigurerAdapter
{
    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver localeResolver = new SessionLocaleResolver();
        Locale defaultLocale = new Locale("en_US");
        localeResolver.setDefaultLocale(defaultLocale);
        return localeResolver;
    }

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

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

我的Thymeleaf页面:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta name="viewport"
        content="width=device-width, initialscale=1, maximum-scale=1.0, user-scalable=no" />
    <title>Home</title>

    <!-- CSS Links -->
</head>
<body>
    <div class="container">
        <div class="row">
            <p th:text="#{welcome}">Hello</p>
        </div>
    </div>
</body>
</html>

并且我在两个消息属性文件中都定义了欢迎消息,并将以下内容放入了application.properties文件中:

spring.messages.basename=messages
spring.messages.encoding=UTF-8

当我点击localhost:8080/home时,它会打印出??welcome_en_us??。我不知道我错过了什么。而且我发现有些人把basename写为“classpath:messages”,这是什么意思?我的意思是我的项目结构不对,应该把属性文件放在其他地方吗?

e0bqpujr

e0bqpujr1#

由于没有人打算张贴这个问题的答案,我张贴一个。
This answer(答案!)与您的问题相关。
它说你把你的默认语言的消息(无论它是英语与否)在 messages.properties,并为您的其他地区的特定文件。
如果 messages.properties 不适用于英语,则为其创建一个 messages_en.properties 文件。

polhcujo

polhcujo2#

我也遇到了同样的问题。我有application.properties和messages.properties文件。我删除了application.properties文件,我没有使用它。删除“application.properties”文件后,它为我工作。

相关问题