Thymeleaf+Springで作成したHTMLで文字化け

Spring MVCのサンプルプロジェクトでViewの描画をthymeleafテンプレートエンジンによるものに変更する」では、Spring+Thymeleafの導入を行った。

そこで作成したHTMLを少し修正して、ボタンをつけてみた。そしたら、ボタンに表示させた日本語が文字化けした。


HTMLは下記のように記述し、metaタグでcharsetは指定してある。

<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring3-3.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Home</title>
</head>
<body>
	<h1>Hello world!</h1>
	<p th:utext="${thymeleaf}">Welcome to our grocery store!</p>
	<form action="/displayTweet">
		<input type="button" value="tweet取得"/>
	</form>
</body>
</html>

◎解決方法
servlet-context.xmlのThymeleafViewResolverの設定にて、文字エンコーディングを指定する。

<beans:bean class="org.thymeleaf.spring3.view.ThymeleafViewResolver">
	<beans:property name="characterEncoding" value="UTF-8" />
	<beans:property name="templateEngine" ref="templateEngine" />
</beans:bean>

これでしっかりとエンコーディングされて文字化けせずに表示された。