【发布时间】:2016-06-25 01:32:32
【问题描述】:
我正在尝试使用 spring boot 在 spring mvc 4 中创建一个简单的国际化示例,但它不起作用。这是我的网络应用程序结构
这是我的 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??。 我不知道我错过了什么。我发现有些人将基本名称写为“classpath:messages”,这是什么意思?我的意思是我的项目结构不正确,应该将属性文件放在其他地方吗?
【问题讨论】:
-
添加
messages.properties。 -
你的项目结构看起来不错,
src/main/resources是一个源文件夹,即classpath中的文件夹。我不明白这里有什么问题,你期望发生什么?实际输出是多少? -
正如 M. Deinum 提到的,如果你将文件 messages.properties 添加到资源中(文件甚至可以是空的),它将开始工作
-
thx all .. 是的,你是对的,正如@M.Deinum 所说,它现在工作正常。但如果我可能会问,为什么需要这样做,特别是我定义了一个默认语言环境来使用 en_US 属性文件?我应该删除 en_US 文件并将 messages.properties 视为默认英文(我的意思是为什么重复)?
-
让我知道您使用的是哪个版本的
Thymeleaf?因为我使用的是相同的结构,但它对我不起作用。
标签: java spring-boot spring-mvc internationalization thymeleaf