CS log

[스프링 입문] view 환경설정 본문

Spring & Spring Boot

[스프링 입문] view 환경설정

sj.cath 2024. 9. 8. 01:06

1. welcome page 만들기

src > resources > static 안에 index.html 파일을 생성해 프론트 화면을 구성해준다.

 

이후 다시 localhost:8080을 띄우면 다음과 같은 홈 화면이 등장한다!

 

참고로 아래 홈페이지 reference 문서에서 필요한 내용들을 찾을 줄 알아야 한다.

 

https://docs.spring.io/spring-boot/docs/2.3.1.RELEASE/reference/html/spring-boot-features.html#boot-features-spring-mvc-welcome-page

 

Spring Boot Features

Graceful shutdown is supported with all four embedded web servers (Jetty, Reactor Netty, Tomcat, and Undertow) and with both reactive and Servlet-based web applications. It occurs as part of closing the application context and is performed in the earliest

docs.spring.io

 

https://www.thymeleaf.org

 

Thymeleaf

Integrations galore Eclipse, IntelliJ IDEA, Spring, Play, even the up-and-coming Model-View-Controller API for Java EE 8. Write Thymeleaf in your favourite tools, using your favourite web-development framework. Check out our Ecosystem to see more integrati

www.thymeleaf.org

 

 

2. controller 동작 만들기

위와 같은 계층구조로 controller와 hello.html을 만들어준다.

 

// HelloController
package hello.hello_spring.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";
    }
}

 

 

<!-- 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>  <!--즉, key가 data이고 value가 hello인 것이다.-->
</body>
</html>

 

그 결과, http://localhost:8080/hello에서 아래와 같은 화면이 출력된다.

 

동작원리는 위와 같다.

* controller가 return하는 hello라는 이름의 html을 찾아가서 랜더링한다.