はじめに
IntelliJでJava SpringBootのプロジェクトを作成で作成したアプリケーションにTymeleafを使ってWebページの作成を行います。
手順
build.gradleの編集
spring-boot-starter-thymeleafを追加します。
build.gradle
dependencies {
// SpringBoot
implementation "org.springframework.boot:spring-boot-starter-web"
testImplementation "org.springframework.boot:spring-boot-starter-test"
implementation "org.springframework.boot:spring-boot-starter-thymeleaf"
Controllerを変更
Controllerを変更し、返却値をテンプレート名(index)に変更します。
package com.ykdevs.SpringBootTest.app;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class IndexController {
@GetMapping("/")
public String index() {
return "index";
}
}
ページを作成
src/main/resources/templates にindex.htmlを作成します。
index.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>テストページ</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
Hello World!!
</body>
</html>
アプリケーションを起動
変数を表示できるように変更
引数にModelクラスを指定して、addAttributeで値を指定します。
package com.ykdevs.SpringBootTest.app;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class IndexController {
@GetMapping("/")
public String index(Model model) {
model.addAttribute("name", "山田 太郎");
return "index";
}
}
テンプレートを編集
index.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>テストページ</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'こんにちは, ' + ${name} + 'さん!'" />
</body>
</html>