一个简单的测试项目,只有一个控制器和html页面,根据客户端语言选择显示语言
html页面如下:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3 th:text="#{home.welcome}">welcome</h3>
</body>
</html>
applicationContext.xml文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="cn.sharpcode" />
<bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
</bean>
<bean id="templateResolver" class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">
<property name="suffix" value=".html" />
<property name="prefix" value="/WEB-INF/templates/" />
<property name="characterEncoding" value="utf-8" />
</bean>
<bean id="viewResolver" class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine" />
<property name="contentType" value="text/html;charset=utf-8" />
<property name="characterEncoding" value="utf-8" />
</bean>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages" />
</bean>
</beans>
messages_zh_CN.properties如下:
home.welcome=欢迎
最后是控制器代码:
@Controller
public class HomeController {
@RequestMapping("home")
public String home(){
return "home";
}
}
整个项目结构:
最后还是得自己解决,把ThymeleafViewResolver的characterEncoding和ResourceBundleMessageSource的defaultEncoding属性都设置为utf-8