๋ฐ์ํ
๐ก MVC pattern
Model, View, Controller
๋ฐ์ดํฐ, ํ๋ฉด, ์๋ฐ์ฝ๋๋ฅผ ๋ถ๋ฆฌํ ๊ฒ์ด๋ค.
์ฝ๋
- templatesํด๋์ htmlํ์ผ ํ๋๋ฅผ ๋ง๋ค์์ต๋๋ค.
๋๋ณด๊ธฐ
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>hello template</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <html> <body> <p th:text="'hello ' + ${name}">hello! template</p> </body> </html> </html>
- Controllerํด๋์ HelloController๋ผ๋ ์๋ฐํ์ผ์ helloMvc๋ผ๋ ๋ฉ์๋๋ฅผ ๋ง๋ญ๋๋ค.
๋๋ณด๊ธฐ
package hello.hellospring.Controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller public class HelloController { @GetMapping("hello") public String hello(Model model) { model.addAttribute("data", "hihi"); return "hello"; } @GetMapping("hello-mvc") public String helloMvc(@RequestParam(name = "name") String name, Model model) { model.addAttribute("name", name); return "hello-template"; } }
- ์๋ฒ์คํ ๊ฒฐ๊ณผ
๐ฟ ์ฝ๋ ์ค๋ช ๐ฟ
- ์น ๋ธ๋ผ์ฐ์ ์์ http://localhost:8080/hello-mvc?name=spring!๋ฅผ ์น๋ฉด
- localhost:8080
๋ก์ปฌํธ์คํธ์ 8080ํฌํธ์์ - /hello-mvc
hello-mvc๋ผ๋ ๋ฉ์๋๋ช ์ ์ฐพ์๊ฐ๋๋ค.
→ @GetMapping("hello-mvc") - ?name=spring!
- ? ๋ท ๋ถ๋ถ์ ์ธ์์ ๋๋ค.
- name์ด๋ ํ๋ผ๋ฏธํฐ์ spring! ์ด๋ ๊ฐ์ ๋ฃ์ด ๋ณด๋
๋๋ค.
- localhost:8080
- Controller
@GetMapping("hello-mvc") public String helloMvc(@RequestParam(name = "name") String name, Model model) { model.addAttribute("name", name); return "hello-template"; }
- @RequestParam(name = "name")
- "name"์ด๋ผ๋ ํ๋ผ๋ฏธํฐ ๊ฐ์ String name์ ๋ด์์ค๋๋ค.
- "name"์ด๋ผ๋ ํ๋ผ๋ฏธํฐ ๊ฐ์ String name์ ๋ด์์ค๋๋ค.
- model.addAttribute("name", name);
- model์ return์ ์ ์ง ์์๋ ์๋์ผ๋ก ๊ฐ์ด ๋ฐํ๋๋ ๋ฐ์ดํฐ์ ๋๋ค.
- addAttribute ๊ฐ์ ๋ด๋ ํจ์์
๋๋ค.
- return "hello-template";
- "hello-template"์ด๋ผ๋ ์ด๋ฆ์ view๋ฅผ ์ฐพ์๊ฐ๋๋ค.
- ์ด๋ ๊ฒ๋ง ์ ์ด๋ ๋์ํ๋ ๊ฑด Thymeleaf ํ
ํ๋ฆฟ ์์ง์ viewResolver๋๋ถ์
๋๋ค.
- @RequestParam(name = "name")
- view
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>hello template</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <html> <body> <p th:text="'hello ' + ${name}">hello! template</p> </body> </html> </html>
- <html xmlns:th="http://www.thymeleaf.org">
- html์์ th๋ผ๋ ์ด๋ฆ์ผ๋ก ํ์๋ฆฌํ๊ฐ ์ฐ๊ฒฐ๋์์ต๋๋ค.
- html์์ th๋ผ๋ ์ด๋ฆ์ผ๋ก ํ์๋ฆฌํ๊ฐ ์ฐ๊ฒฐ๋์์ต๋๋ค.
- <p th:text="'hello ' + ${name}">hello! template</p>
- ํ์๋ฆฌํ ํ ํ๋ฆฟ ์์ง์ ์ด์ฉํด model์ ๋ด๊ฒจ์จ name์ด๋ ์ด๋ฆ์ ๋ฐ์ดํฐ๋ฅผ ๋์ ํฉ๋๋ค.
- <html xmlns:th="http://www.thymeleaf.org">
โป ์ฐธ์กฐ : https://www.inflearn.com/roadmaps/373
๋ฐ์ํ
'๐ Spring > ๐ Spring Boot' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[SpringBoot]ํ์๊ด๋ฆฌ-๋น์ง๋์ค ์๊ตฌ์ฌํญ ์ ๋ฆฌ (0) | 2025.01.04 |
---|---|
[SpringBoot]์น ๊ฐ๋ฐ ๊ธฐ์ด-API @ResponseBody (0) | 2025.01.04 |
[SpringBoot]์น ๊ฐ๋ฐ ๊ธฐ์ด-์ ์ ์ปจํ ์ธ (0) | 2025.01.03 |
[SpringBoot][Gradle]์ ๋ฌธ-๋น๋ํ๊ณ ์คํ (1) | 2025.01.03 |
[SpringBoot][Grandle][VScode]devtools:์๋ฒ ์ฌ์์์์ด ๋ฐ์ํ๊ธฐ (0) | 2025.01.03 |