この記事はこれの続きです
Entityクラス、Repositoryクラス、Serviceクラスは作成済の想定です。
Controllerクラス
Modelクラスを使って addAttribute()
でThymeleafで参照する変数にセットするのがポイント。
DemoController
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class DemoController {
@Autowired
UnkoService unko_service;
@GetMapping("/")
public String getIndex(Model model) {
model.addAttribute("unko_list", unko_service.findAll());
return "/index";
}
}
Thymeleafのテンプレートhtml
th:each
でループ、 th:text
で変数の値を表示するのがポイント。
index.html
<!DOCTYPE html>
<html lang="ja" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<body>
<table>
<tr>
<th>record_id</th>
<th>test_val</th>
</tr>
<tr th:each="unko : ${unko_list}">
<td><div th:text="${unko.record_id}"></div></td>
<td><div th:text="${unko.test_val}"></div></td>
</tr>
</table>
</body>
</html>
実行結果
この記事の続き
バージョン
Microsoft Windows [Version 10.0.19045.4170]
Spring Boot v3.1.9