๋ฐ์ํ
Welcome Page ๋ง๋ค๊ธฐ
- src-main-resources-staticํด๋์ ์ฐ์ปดํ์ด์ง(์์ํ์ด์ง)์ธ index.htmlํ์ผ์ ๋ง๋ค์ด์ค๋ค.
โป ์ฐธ์กฐ : 2025.01.02 - [๐ Spring/๐ Spring Boot] - [SpringBoot]ํ์ํ ๊ธฐ๋ฅ ์ฐพ๋ ๋ฒ
- ๊ฐ๋จํ ์ ์ ํ์ด์ง๋ฅผ ๋ง๋ค์ด์คฌ๋ค.
↓ ์ฝ๋
๋๋ณด๊ธฐ<!DOCTYPE html> <html lang="ko"> <head> <titl>Hello</titl> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <html> <body> Hello <a href="/hello">hello</a> </body> </html> </html>
Thymeleaf
- Controller๋จ์ ๋ง๋ค์๋ค.
- Controller๋ javaํ์ผ๋ค ์ค ์์ ์ ์ด๋ผ ํ ์ ์๋ค.
- @Controller : ์ด๋
ธํ
์ด์
@์ ์ด์ฉํด ์คํ๋ง์ ํด๋น ํด๋์ค๊ฐ ์ปจํธ๋กค๋ฌ๋ผ๋ ๊ฒ์ ์๋ฆฐ๋ค.
- @GetMapping("๋ฉ์๋๋ช
") : ํ๋ฉด๋จ์์ ํด๋น ๋ฉ์๋๋ช
์ผ๋ก ์ปจํธ๋กค๋ฌ๋ฅผ ์ฐพ์์จ๋ค.
- Mode : MVCํจํด์ ๊ทธ ๋ชจ๋ธ์ด๋ค. ๋ฐ์ดํฐ๊ฐ ๋ด๊ฒจ์๋ค.
- model.addAttribute(name, value) : ๋ชจ๋ธ์ ๋ฐ์ดํฐ๋ฅผ ๋ด๋๋ค.
- return "hello" : hello๋ผ๋ ํ๋ฉด์ผ๋ก model์ ๋์ ธ์ค๋ค.
- ๐ ์ด ๋ ํ๋ฉด์ ์ฐพ์๊ฐ๊ฒ ํด์ฃผ๋ ๋ทฐ ๋ฆฌ์กธ๋ฒ(viewResolver) ์ธํฐํ์ด์ค๊ฐ ์๋์ผ๋ก ์๋ํ๋ค.
templates/hello.html์ด ์ฐพ์๊ฐ๋๋ก ์ธํ ๋์ด์๋ค. (Thymeleafํ ํ๋ฆฟ ์์ง์ด ์ฒ๋ฆฌ)
- ๐ ์ด ๋ ํ๋ฉด์ ์ฐพ์๊ฐ๊ฒ ํด์ฃผ๋ ๋ทฐ ๋ฆฌ์กธ๋ฒ(viewResolver) ์ธํฐํ์ด์ค๊ฐ ์๋์ผ๋ก ์๋ํ๋ค.
- @Controller : ์ด๋
ธํ
์ด์
@์ ์ด์ฉํด ์คํ๋ง์ ํด๋น ํด๋์ค๊ฐ ์ปจํธ๋กค๋ฌ๋ผ๋ ๊ฒ์ ์๋ฆฐ๋ค.
- ↓ ์ฝ๋
๋๋ณด๊ธฐ
package hello.hellospring.Controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @Controller public class HelloController { @GetMapping("hello") public String hello(Model model) { model.addAttribute("data", "hello!!"); return "hello"; } }
- Controller๋ javaํ์ผ๋ค ์ค ์์ ์ ์ด๋ผ ํ ์ ์๋ค.
- ํ๋ฉด๋จ ๋ง๋ค๊ธฐ
- <html xmlns:th="http://www.thymeleaf.org"> : ํ์๋ฆฌํ๊ฐ ์ฐ๊ฒฐ๋์ด th:๋ผ๋์ด๋ฆ์ผ๋ก ์ฌ์ฉํ ์ ์๊ฒ ํด์ค๋ค.
- <p th:text="'์๋
ํ์ธ์. ' + ${data}" >์๋
ํ์ธ์. ์๋</p>
- th:text: ํ์๋ฆฌํ ๊ธฐ๋ฅ ์ค text๋ผ๋ฅธ ๊ธฐ๋ฅ์ ์ด์ฉํ๋ค.
- ${ data } : ์ปจํธ๋กค๋ฌ๋จ์์ model์ ๋ด๊ธด data๋ผ๋ ์ด๋ฆ์ ๊ฐ์ ๊ฐ์ ธ์ '์๋'์ด๋ ๋ถ๋ถ์ ์นํํ๋ค.
-
๋๋ณด๊ธฐ์ฝ๋
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <titl>Hello</titl> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <html> <body> <p th:text="'์๋ ํ์ธ์. ' + ${data}" >์๋ ํ์ธ์. ์๋</p> </body> </html> </html>
- <html xmlns:th="http://www.thymeleaf.org"> : ํ์๋ฆฌํ๊ฐ ์ฐ๊ฒฐ๋์ด th:๋ผ๋์ด๋ฆ์ผ๋ก ์ฌ์ฉํ ์ ์๊ฒ ํด์ค๋ค.
- ์๋ฃ! pํ๊ทธ์๋ ์คํ๋ง๊ณผ ํ์๋ฆฌํ๋ฅผ ์ด์ฉํด '์๋' → 'hello'๋ก ๋ฌธ์๊ฐ ์นํ๋์๋ค.
โป ์ฐธ์กฐ : https://www.inflearn.com/roadmaps/373
๋ฐ์ํ
'๐ Spring > ๐ Spring Boot' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[SpringBoot][Gradle]์ ๋ฌธ-๋น๋ํ๊ณ ์คํ (1) | 2025.01.03 |
---|---|
[SpringBoot][Grandle][VScode]devtools:์๋ฒ ์ฌ์์์์ด ๋ฐ์ํ๊ธฐ (0) | 2025.01.03 |
[SpringBoot]ํ์ํ ๊ธฐ๋ฅ ์ฐพ๋ ๋ฒ (0) | 2025.01.02 |
[SpringBoot][Gradle]์ ๋ฌธ-๋ผ์ด๋ธ๋ฌ๋ฆฌ (1) | 2025.01.02 |
[SpringBoot][Gradle]์ ๋ฌธ-ํ๋ก์ ํธ ์์ฑ (5) | 2024.10.23 |