@Controller
public class HelloController {
@GetMapping("hello")
public String hello(Model model) {
model.addAttribute("data", "hello!!!");
return "hello";
}
}
์ฌ๊ธฐ์ model์ ์ด๋์ ๋์ค๋๊ฑฐ๊ณ ์ญํ ์ด ๋ญ๊น์?
โ Model์ ์ด๋์ ๋์ฌ๊น?
public String hello(Model model)
์ฌ๊ธฐ์ Model์ ์คํ๋ง์ด ์๋์ผ๋ก ์ฃผ์ ํด์ฃผ๋ ๊ฐ์ฒด(=์์กด์ฑ ์ฃผ์ )์ด๋ค.
- @GetMapping์ ์ํด HTTP ์์ฒญ์ด ์ค๋ฉด,
- ์คํ๋ง์ด ํด๋น ๋ฉ์๋๋ฅผ ํธ์ถํ๋ฉด์ Model ๊ฐ์ฒด๋ฅผ ์ปจํธ๋กค๋ฌ ๋ฉ์๋์ ํ๋ผ๋ฏธํฐ๋ก ์๋ ์ ๋ฌ
- ๊ฐ๋ฐ์๋ ๊ทธ๋ฅ model์ ๋ฐ์์ ์ฌ์ฉํ๋ฉด ๋๋ ๊ฑฐ๋ค. ๋ฐ๋ก ์์ฑํ๊ฑฐ๋ ๊ด๋ฆฌํ ํ์ ์์ด!
๐ฏ Model์ ์ญํ
๐ ๋ทฐ(View)๋ก ๋ฐ์ดํฐ๋ฅผ ๋๊ธฐ๋ ์ญํ ์ ํ๋ค.
- ์ปจํธ๋กค๋ฌ์์ ๋ฐ์ดํฐ๋ฅผ ๋ง๋ค๊ณ ,
- model.addAttribute("key", value) ๋ก ์ถ๊ฐํ๋ฉด,
- ๋ทฐ ํ ํ๋ฆฟ(์: Thymeleaf)์์ ${key}๋ก ์ ๊ทผ ๊ฐ๋ฅํ๋ค.
๐ ํ๋ฆ ์์
@GetMapping("hello")
public String hello(Model model) {
model.addAttribute("data", "hello!!!");
return "hello";
}
- ๋ธ๋ผ์ฐ์ ๊ฐ /hello ์์ฒญ
- HelloController.hello() ์คํ
- model์ "data" = "hello!!!" ์ ์ฅ
- ๋ทฐ ์ด๋ฆ "hello" ๋ฐํ → resources/templates/hello.html ๋ ๋๋ง
- ํ ํ๋ฆฟ์์ ${data}๋ฅผ "hello!!!"๋ก ์นํ
๐ผ๏ธ View (Thymeleaf) ์์
<!-- hello.html -->
<html>
<body>
<p th:text="${data}">๊ธฐ๋ณธ ํ
์คํธ</p>
</body>
</html>
์ด๋ ๊ฒ ํ๋ฉด ํ๋ฉด์ hello!!!๊ฐ ์ถ๋ ฅ๋๋ค.
๐ ์ ๋ฆฌ
ํญ๋ชฉ ์ค๋ช
| Model | ๋ทฐ๋ก ๋ฐ์ดํฐ๋ฅผ ์ ๋ฌํ๊ธฐ ์ํ ๊ฐ์ฒด |
| ์์ฑ ๋ฐฉ๋ฒ | ์คํ๋ง์ด ์๋์ผ๋ก ์ปจํธ๋กค๋ฌ์ ์ฃผ์ |
| ์ฃผ์ ๋ฉ์๋ | model.addAttribute("key", value) |
| ๋ทฐ ์ฌ์ฉ๋ฒ | ${key} ํํ๋ก ํ์๋ฆฌํ(Thymeleaf)์์ ์ ๊ทผ |
'๐ฅ๏ธ ์น(Web) > ์คํ๋ง' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| ์คํ๋ง setName (0) | 2025.04.19 |
|---|---|
| Repository ์ธํฐํ์ด์ค (0) | 2025.04.19 |
| DTO, Entity, Mapper (0) | 2025.04.18 |
| ์คํ๋ง ๋ ์ด์ด ๊ตฌ์กฐ (0) | 2025.04.18 |
| ์คํ๋ง ๋ถํธ ํ๋ก์ ํธ ๊ตฌ์กฐ (0) | 2025.04.18 |