Controller → Model → Viewpackage com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class GreetingController {
@GetMapping("/greet")
public String greet(Model model) {
model.addAttribute("name", "ユーザーさん");
return "greet"; // templates/greet.html を表示
}
}
Model:Viewに値を渡すデータのコンテナ
addAttribute("key", value)で渡すgreet.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Greeting</title>
</head>
<body>
<h1 th:text="'こんにちは、' + ${name} + '!'"></h1>
</body>
</html>
こんにちは、ユーザーさん!th:text:テキストを埋め込む
<p th:text="${msg}"></p>
th:href:リンクのパスを設定
<a th:href="@{/home}">Home</a>
th:if, th:unless:条件分岐
<p th:if="${login}">ようこそ</p>
th:each:ループ
<li th:each="item : ${list}" th:text="${item}"></li>
th:<object> / *{}:フォームオブジェクトを参照
<input th:field="*{name}">
単一の値
model.addAttribute("msg", "Hello");
${msg}
配列:リスト
model.addAttribute("list", "users");
th:each="u : ${list}"
DTOやEntity
model.addAttribute("user", user);
${user.name}