Hello, Thymeleaf

Spring BootではJSPではなく、Thymeleaf(タイムリーフ)が推奨されてるみたい。
ちょっと使ってみました。

[広告]
[広告]

SpringBoot webアプリ環境設定 からの変更概要

src
├─main
│  ├─groovy
│  │  └─sample
│  │      │  Application.groovy
│  │      │  
│  │      └─app
│  │          └─product
│  │                  ProductController.groovy  // 新規作成
│  │                  
│  ├─java
│  └─resources
│      └─templates
│          └─product
│                  index.html                    // 新規作成
│                  
└─test
    ├─groovy
    ├─java
    └─resources

build.gradle

・dependenciesに追加
dependencies {
    compile('org.codehaus.groovy:groovy:2.4.12')

    compile('org.springframework.boot:spring-boot-starter-web')
    providedRuntime('org.springframework.boot:spring-boot-starter-tomcat')
    testCompile('org.springframework.boot:spring-boot-starter-test')

    // 以下を追加
    compile 'org.springframework.boot:spring-boot-starter-thymeleaf'
}

コントローラを作成

・sample.app.product.ProductControllerを作成
package sample.app.product

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
@RequestMapping("product")
class ProductController {

    @RequestMapping(value="index", method=RequestMethod.GET)
    String index(Model model) {
        // Thymeleafに渡すオブジェクトを設定
        model.addAttribute("title", "Hello, world")

        // resource/templates/product/index.htmlの読み出し
        return "product/index"
    }
}

Thymeleafを作成

・resources/templates/product/index.htmlを作成
<html xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8" />
    </head>
    <body>
        <h1 th:text="${title}"></h1>
    </body>
</html>

実行結果

        

コメントを残す

メールアドレスが公開されることはありません。