1
0

SpringBootでEntityで取得したMySQLのレコード値をThymeleafで表示

Last updated at Posted at 2024-03-24

この記事はこれの続きです

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>

実行結果

image.png

この記事の続き

バージョン

Microsoft Windows [Version 10.0.19045.4170]
Spring Boot v3.1.9

1
0
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
1
0