
/list๋ก ์ ์ํ๋ฉด ์ํ ๋ชฉ๋ก ํ์ด์ง(list.html)๋ฅผ ์ ์กModel์ ๋ด์ ๋ฐ์ดํฐ๋ฅผ Thymeleaf๋ก ๋ฐ์ธ๋ฉfindAll() ๊ฒฐ๊ณผ๋ฅผ th:each๋ก ๋ ๋๋งํ๋ ๋ฐํ| ํค์๋ | ์ค๋ช |
|---|---|
| Controller | API๋ฅผ ๋ด๋ ํด๋์ค. ์์ฒญ์ ๋ฐ์ ์ด๋ค ๋ทฐ๋ฅผ ๋ฐํํ ์ง ๊ฒฐ์ |
@GetMapping | ํน์ URL์ GET ์์ฒญ์ ์ฒ๋ฆฌํ๋ API ์ ์ |
| templates/ | Thymeleaf ํ
ํ๋ฆฟ ์์น. return "list" โ templates/list.html ๋ ๋ |
| Model | ์ปจํธ๋กค๋ฌ โ ํ ํ๋ฆฟ์ผ๋ก ๋ณด๋ด๋ ๋ฐ์ดํฐ ์ปจํ ์ด๋ |
th:text | ํ๊ทธ ๋ด๋ถ ํ ์คํธ๋ฅผ ์๋ฒ ๋ฐ์ดํฐ๋ก ์นํ |
| Thymeleaf | ์๋ฒ ๋ฐ์ดํฐ โ HTML์ ์ฃผ์ ํ๋ ํ ํ๋ฆฟ ์์ง |
๐ src/main/java/com/apple/shop/item/ItemController.java
package com.apple.shop.item;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class ItemController {
@GetMapping("/list")
String list(Model model){
model.addAttribute("name", "ํ๊ธธ๋"); // ์์ ๋ฐ์ดํฐ
return "list"; // templates/list.html
}
}
package com.apple.shop.item;)return "list"์ฒ๋ผ ํ์ฅ์ ์๋ต ๊ถ์ฅ(Thymeleaf ๊ท์น)๐ src/main/resources/templates/list.html
<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>์ํ ๋ชฉ๋ก</title>
</head>
<body>
<div>
<img src="https://placehold.co/300" alt="thumb">
<h4 th:text="${name}">๋ฐ์ง</h4>
<p>7์ต</p>
</div>
<div>
<img src="https://placehold.co/300" alt="thumb">
<h4>์
์ธ </h4>
<p>8์ต</p>
</div>
</body>
</html>
xmlns:th ์ ์ธ์ผ๋ก Thymeleaf ์์ฑ ์ฌ์ฉ ๊ฐ๋ฅ${name} โ ์ปจํธ๋กค๋ฌ์์ ๋ณด๋ธ Model ๋ฐ์ดํฐ๐ build.gradle
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web'
}
http://localhost:8080/list ์ ์ <h4>์ ํ๊ธธ๋์ด ๋ณด์ด๋ฉด ์ฑ๊ณต(์์ ๋ฐ์ดํฐ ๋ฐ์ธ๋ฉ ํ์ธ) th:each๋ก ๋ชฉ๋ก ๋ฐ๋ณต ๋ ๋๋งfindAll() ๊ฒฐ๊ณผ๋ฅผ ๋ฐ์ th:each๋ก ๋ฐ๋ณต ์ถ๋ ฅ/list API์์ Model๋ก ๋ฐ์ดํฐ ์ ๋ฌ โ list.html์์ Thymeleaf ๋ฐ์ธ๋ฉreturn "๋ทฐ์ด๋ฆ"์ผ๋ก ๋ ๋