๐Ÿ–ฅ๏ธ Web Development Study/Back-End

[Back-End] ์Šคํ”„๋ง ์ž…๋ฌธ :: View ํ™˜๊ฒฝ ์„ค์ •

ibelieveinme 2024. 5. 27. 01:59
728x90

 

1. Welcome page ๋งŒ๋“ค๊ธฐ

static ์ด๋ผ๋Š” ์ •์ ํด๋” ๋ฐ‘์— index.html ์ด๋ผ๋Š” ์ด๋ฆ„์˜ ํŒŒ์ผ์„ ๋งŒ๋“ค์–ด์ฃผ๋ฉด ์ž๋™์œผ๋กœ welcome page ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•œ๋‹ค.

 

https://docs.spring.io/spring-boot/reference/web/servlet.html

 

Servlet Web Applications :: Spring Boot

For servlet application, Spring Boot includes support for embedded Tomcat, Jetty, and Undertow servers. Most developers use the appropriate “Starter” to obtain a fully configured instance. By default, the embedded server listens for HTTP requests on po

docs.spring.io

์ฐธ๊ณ ๋กœ Spring ๋ฒ”์œ„๊ฐ€ ๋„ˆ๋ฌด ๊ด‘๋Œ€ํ•ด์„œ Spring boot document ์— ๊ฐ€์„œ ๋‚ด์šฉ์„ ๋น ๋ฅด๊ฒŒ ์ฐพ๊ณ  ๊ทธ๋•Œ๊ทธ๋•Œ ํ™•์ธํ•˜๋Š”๊ฒŒ ์ค‘์š”ํ•˜๋‹ค.

 

2. Template ๋งŒ๋“ค๊ธฐ 

์œ„์—์„œ ๋งŒ๋“  ํ™”๋ฉด์€ ํŒŒ์ผ์„ ํ†ต์งธ๋กœ ๋˜์ ธ์ค˜์„œ ๋ณด์—ฌ์ง„ ํ™”๋ฉด์ด๋‹ค. ํ”„๋กœ๊ทธ๋ž˜๋ฐ์ด๋ผ ํ•  ์ˆ˜๊ฐ€ ์—†๋‹ค.

thymeleaf ํ…œํ”Œ๋ฆฟ ์—”์ง„์„ ์จ์„œ ํ”„๋กœ๊ทธ๋ž˜๋ฐ ๋œ ํŽ˜์ด์ง€๋กœ ๋งŒ๋“ค์–ด๋ณด์ž.

 

 

src/main/java/.../firstproject/controller/HelloController.java

src/main/java/resources/templates/Hello.html

 

controller ๋ผ๋Š” ํŒจํ‚ค์ง€์™€ HelloController.java ๋ผ๋Š” ํŒŒ์ผ, Hello.html ์ด๋ผ๋Š” ํ…œํ”Œ๋ฆฟ ํŒŒ์ผ์„ ๋งŒ๋“ค์–ด ์ฃผ์ž.

 

 

// HelloController.java

package com.yoonsung.firstproject.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";
    }
}

@GetMapping ์€ hello ๋ผ๋Š” url ์— ๋งค์นญํ•œ๋‹ค๋Š” ๋œป. http://localhost:8080/hello

return "hello" ๋Š” resources/templates ๊ฒฝ๋กœ์— hello ๋ผ๋Š” ์ด๋ฆ„์˜ view html ํŒŒ์ผ์„ ์ฐพ์•„๊ฐ€๋ผ๋Š” ๋œป.

 

์ฆ‰, Spring Boot๋Š” controller ์—์„œ return ๊ฐ’์œผ๋กœ ๋ฌธ์ž๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋ฉด viewResolver ๊ฐ€ ํ™”๋ฉด์„ ์ฐพ์•„์„œ ์ฒ˜๋ฆฌํ•˜๋Š” ๋™์ž‘ํ๋ฆ„์ด๋‹ค.

 

 

// Hello.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'์•ˆ๋…•ํ•˜์„ธ์š”. ' + ${data}" >์•ˆ๋…•ํ•˜์„ธ์š”. ์†๋‹˜</p>
</body>
</html>

data ๊ฐ€ HelloController.java ์—์„œ ์“ด data ๋กœ ๋ณ€๊ฒฝ์ด ๋œ๋‹ค.

 

 

3. ํ”„๋กœ์ ํŠธ ์‹คํ–‰ ๋ฐ ํ™•์ธ

http://localhost:8080/hello ๋ฅผ ์‹คํ–‰ํ•˜๋ฉด ์œ„์™€ ๊ฐ™์ด ๋ฐ์ดํ„ฐ๊ฐ€ ๋ณ€๊ฒฝ๋œ ํ™”๋ฉด์ด ์ž˜ ๋‚˜์˜จ๋‹ค.

728x90