前回、Spring MVCプロジェクトを作成した際は、画面がJSPで作成されていたが、今回はThymeleafを利用するHTMLファイルに変更してみたので、そのサンプルプログラムを共有する。
前提条件
下記記事の実装が完了していること。
サンプルプログラムの実行結果
上記前提条件の記事の「Spring MVCプロジェクトの実行」に記載した内容と同じ結果となる。
サンプルプログラムの作成
作成したサンプルプログラムの構成は以下の通り。

なお、上記の赤枠は、前提条件のプログラムから変更したプログラムである。
pom.xmlに追加した内容は以下の通りで、thymeleaf-spring3をライブラリに追加している。なお、今回はSpringフレームワークのバージョンが「3.1.1.RELEASE」なので、「thymeleaf-spring4」でなく「thymeleaf-spring3」を追加している。
<!-- Thymeleaf -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring3</artifactId>
<version>3.0.11.RELEASE</version>
</dependency>また、servlet-context.xmlに追加した内容は以下の通りで、JSPを読み込む設定を削除し、Thymeleafを読み込む設定(templateResolver, templateEngine, ThymeleafViewResolver)を追加している。ここでは「/WEB-INF/templates/」フォルダ下のHTMLファイルを読み込めるようにしている。
<!-- Thymeleafの読み込み -->
<beans:bean id="templateResolver" class="org.thymeleaf.spring3.templateresolver.SpringResourceTemplateResolver">
<beans:property name="prefix" value="/WEB-INF/templates/" />
<beans:property name="suffix" value=".html" />
<beans:property name="templateMode" value="HTML5" />
<beans:property name="characterEncoding" value="UTF-8" />
</beans:bean>
<beans:bean id="templateEngine" class="org.thymeleaf.spring3.SpringTemplateEngine">
<beans:property name="templateResolver" ref="templateResolver" />
</beans:bean>
<beans:bean class="org.thymeleaf.spring3.view.ThymeleafViewResolver">
<beans:property name="templateEngine" ref="templateEngine" />
<beans:property name="characterEncoding" value="UTF-8" />
</beans:bean>また、遷移先のHTMLファイルの内容は以下の通り。
<!DOCTYPE html>
<html lang="ja" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Home</title>
</head>
<body>
<h1>Hello world! </h1>
<P th:text="|The time on the server is ${serverTime}.|"></P>
</body>
</html>その他、今回ソースコード内容は、以下のサイトを参照のこと。
https://github.com/purin-it/java/tree/master/spring-mvc-thymeleaf/demo
なお、今回は「pom.xml」を変更しているので、以下のように、Mavenメニューからプロジェクトの更新を行っている。


また、更新後のMaven依存関係は以下の通りで、下記赤枠のthymeleaf関連のjarファイルが確認できる。

要点まとめ
- Spring MVCプロジェクトでThymeleafを利用するには、thymeleaf-spring3ライブラリを追加し、「servlet-context.xml」にThymeleafを読み込む設定を追加すればよい。





