プログラマーの調べ物

プログラマーが調べ物をするときに役に立つサイトを作ります。

Spring BootでテンプレートエンジンThymeleafを使って画面表示

テンプレートエンジンとしてThymeleafを使ってみます。

まず、pom.xmlに以下のように依存性を追加します。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

次に、Controllerを作成します。

package com.example;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class HelloController {
    
    @RequestMapping("/hello")
    public String Hello(Model model) {
        model.addAttribute("hello", "Hello Thymeleaf World!");
        return "hello";
    }
}

このControllerで返す「Hello Thymeleaf World」を表示させるテンプレートファイルを作成します。 場所は、

/src/main/resource/templates/hello.htmlに作成します。 Spring Bootの自動設定では、TemplateResloverがビュー名につけるプレフィックスとサフィックスのデフォルト値は、それぞれ"classpath:/templates/"と".html"になるためです。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="utf-8"></meta>
  <title>example</title>
</head>
<body>
<p>
  <span th:text="${hello}"></span>
</p>
</body>
</html>

これで、http://localhost:8080/helloにリクエストをとばすと、

Hello Thymeleaf World!

と表示されます。