LoginSignup
10
10

More than 5 years have passed since last update.

Thymeleafを導入してみる

Last updated at Posted at 2016-07-31

Thymeleafって何?

ThymeleafはJavaのテンプレートエンジンです。
動的に表示する要素はhtmlの属性で記述するので、アプリケーションが動いていない状態でも画面のデザインなどを確認できるというメリットがあります。

JSPを使って開発をしているとデプロイしないと画面が確認できないのが煩わしいので使ってみたので、
備忘録がてら書き残していきます。

Thymeleafのダウンロード

今回はMavenを利用して取得します。
pom.xmlに以下を追加します。

pom.xml
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring4</artifactId>
    <version>3.0.0.RELEASE</version>
</dependency>

バージョンは3.0.0を利用します。
Springも利用するので、thymeleaf-springも導入しています。

Thymeleafの設定

続いて、Springの設定ファイルに以下のbean定義を追加してThymeleafを利用できるようにします。
Spring自体の設定については割愛しています。

spring-mvc.xml
<bean id="templateResolver" class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">
  <property name="prefix" value="/WEB-INF/views/" />
  <property name="suffix" value=".html" />
  <property name="templateMode" value="HTML5" />
  <property name="characterEncoding" value="UTF-8" />
</bean>

<bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
  <property name="templateResolver" ref="templateResolver" />
</bean>

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

templateResolverのprefix、suffixは環境によって書き換える必要があります。
今回の環境は「/WEB-INF/views/」配下に「hogehoge.html」のような形でviewファイルを配置するので、上記のように設定しています。

詳しくは以下の公式ドキュメントを参照してください。
http://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html

Thymeleafを動かしてみる

以下のようなControllerクラスとhtmlファイルを作成します。

HelloController.java
@Controller
public class HelloController {
    @RequestMapping(value = "", method = {RequestMethod.GET, RequestMethod.POST})
    public String home(Model model) {
        model.addAttribute("hello", "Hello Thymeleaf!!");
        return "sample";
    }
}
sample.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
  <head>
    <meta charset="UTF-8"/>
    <title>Thymeleaf</title>
  </head>
  <body>
    <span th:text="${hello}">この部分が動的に置き換えられます</span>
  </body>
</html>

上記のhtmlを直接開くと「この部分が動的に置き換えられます」という文字が表示されますが、APサーバを起動してアクセスすると、Thymeleafがその文字列をControllerから与えられた値に置き換えます。

そのため、APサーバを起動してアクセスし、「Hello Thymeleaf!!」という文字列が表示されていれば、Thymeleafが正しく動作していることになります。

以上でThymeleafの導入は完了です。

10
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
10