JavaなテンプレートエンジンのThymeleafを試してみる

昨日の夜中にFacebook眺めてたら、友人の@bufferingsが興味深い事をポストしてたので、 自分もそういうのやりたいな、と。そんなこんなでThymeleafを試してみました。   環境はこないだ作ったEclipseGlassFishなアレ、、でやろうとしたら途中で 挫折したので結局Spring&tc Serverで。。。     ■ Dynamic Web Project作ります       ■ Thymeleafのライブラリを取り込みます   小さくてみずらいのですが、JavaEEEclipseってMaven入ってないのね。。(なんで?)   MavenEclipseプラグインをインストールして、、   とかやってたら何かEclipseのプロジェクトでエラーが出てやがる。。

Referenced file contains errors (http://java.sun.com/xml/ns/javaee/javaee_5.xsd). For more information, right click on the message in the Problems View and select "Show Details..."

  詳細みると↓こんな感じ。   とりあえず、今その辺に使ってる時間ないのでEclipseからエラーをDeleteして、 pom.xmlとか書いてたらなんか面倒くさくなってきました。。     ■ SpringMVCだと…?   ↓みてたら、、

It provides an optional module for integration with Spring MVC, so that you can use it as a complete substitute of JSP in your applications made with this technology, even with HTML5.   Spring MVC用の拡張モジュール的なのがあって、完全にJSPの変わりになりやす, HTML5でもね。

  って事なので、久しぶりにSTS立ち上げて、、   SpringMVCなプロジェクト作って、   pom.xmlに↓突っ込んでやります。

<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf</artifactId>
    <version>2.0.16</version>
</dependency>
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring3</artifactId>
    <version>2.0.16</version>
</dependency>

  #やっぱ慣れてるこのやり方の方が全然早いなぁ。何かと。。     ■ Thymeleafってどんなもんか   ↓にチュートリアルがあるので、ソレに沿って… http://www.thymeleaf.org/doc/Tutorial%20-%20Using%20Thymeleaf%2020130224.pdf   Thymeleaf's core is a DOM processing engine とか、 http://www.thymeleaf.org/fromhtmltohtmlviahtml.html をまずは嫁的な事かいてありますが、先進みますw   8ページ目にようやくそれっポイ記述が出て来ました。

~略~
TemplateEngine templateEngine = GTVGApplication.getTemplateEngine();
~略~
controller.process(request, response, this.servletContext, templateEngine);
~略~

ほうほうって感じっすね。   んじゃどーやってテンプレートエンジンの設定するんざましょって事なのですが、 ↓リゾルバ君にセットしてエンジンのインスタンスに詰めてやるって感じ。

public class GTVGApplication {
  ...
  private static TemplateEngine templateEngine;
  ...
  static {
    initializeTemplateEngine();
  }
  private static void initializeTemplateEngine() {
    ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
    // XHTML is the default mode, but we will set it anyway for better understanding of code
    templateResolver.setTemplateMode("XHTML");
    // This will convert "home" to "/WEB-INF/templates/home.html"
    templateResolver.setPrefix("/WEB-INF/templates/");
    templateResolver.setSuffix(".html");
    // Set template cache TTL to 1 hour. If not set, entries would live in cache until expelled by LRU
    templateResolver.setCacheTTLMs(3600000L);
    templateEngine = new TemplateEngine();
    templateEngine.setTemplateResolver(templateResolver);
    ...
  }

  そしてHTML。 ↓って事なので、Velocityの時の.vmとかじゃなくて.htmlでイケます、と。

// This will convert "home" to "/WEB-INF/templates/home.html" templateResolver.setPrefix("/WEB-INF/templates/");

  ↓こんな感じになるようです。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Good Thymes Virtual Grocery</title>
    <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>
  </head>
  <body>
    <p th:text="#{home.welcome}">Welcome to our grocery store!</p>
  </body>
</html>

  なんとなく分かりました。     ■ SpringMVCでThymeleaf   ↓にSpring用のドキュメントがあったので今度はそれを読んでみます。 http://www.thymeleaf.org/doc/Tutorial%20-%20Thymeleaf%20+%20Spring%203%2020130224.pdf   bean定義に↓こんな風にJSPのアレはコメントアウトしてThymeleafのを追加してやります。

<!--
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/WEB-INF/views/" />
    <beans:property name="suffix" value=".jsp" />
</beans:bean>
-->
<beans:bean id="templateResolver" class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
    <beans:property name="prefix" value="/WEB-INF/templates/" />
    <beans:property name="suffix" value=".html" />
    <beans:property name="templateMode" value="HTML5" />
</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:bean>

  これまた何か疲れてきたな、、って思ってググったところ、、 ↓コレは神ブログ。。 step by step: Spring + Thymeleafでデザインの分離を進める(のとっかかり) [Spring Framework Advent Calendar 2012 5日目 #jsug   SpringMVCのHomeControllerとhome.jspはデフォルトで↓こんな感じでサーバーの日付を返すのですが、 それぞれほんのチョコっと変えます。   Controller。コントローラーからの出力って分かりやすいように[Controller]って付けました。

//model.addAttribute("serverTime", formattedDate );
String message = "  [Controller]The time on the server is " + formattedDate + ". ";
model.addAttribute("serverTimeMessage", message );

  home.jspはtemplatesに移動させてhome.htmlに名前を変更した後、 ↓こんな感じで。こちらもピュアなHTMLな場合に分り易いように[Browser]って付けました。   ブラウザからみてみると、、   サーバー立てたアプリにアクセスしてみると、、     (Springなら)なかなかお手軽で良さげじゃないですか。   Thymeleafは思想からして良さげっぽいのでコレに食らいついていくだけで、 技術者としてイイ事ありそうな気がしてきました。     ■ 感想   Seasar2いじってた頃、HTMLでブラウザに表示させる事ができるテンプレートエンジンは既にあって。 Seasar2は四半期毎かなんかでカンファレンスがあって、それに出てれば何かとキャッチアップ出来て。   今はこうやってon goingなプロジェクトを英語で追わなきゃいけなくて。 大変だなーって思うけれども、グローバルなプロジェクトとか考えたら避けては通れないのだから、 頑張らなきゃなーと思う今日この頃でございます。    

SpringによるWebアプリケーションスーパーサンプル 第2版
株式会社クロノス 阪田 浩一
ソフトバンククリエイティブ
売り上げランキング: 95,102