Web/Spring

[Spring] 정적 / 템플릿 Welcome Page 만들기

728x90

 

지난 글에서 프로젝트를 실행했을 때, localhost를 통해 접속하면 다음과 같은 화면이 나왔었습니다!

프로젝트 내용이 아무것도 없기 때문에 위와 같은 에러가 떴죠?!

이렇게 localhost:8080으로 접속했을 때 뜨는 첫 페이지! welcome page를 만들어보도록 하겠습니다 🧨🧨🧨

 

 

 

 

> static Welcome Page 만들기

1. src > main > resources > static 에 index.html 파일 생성

 

 

 

2. 다음과 같은 내용 입력

<!DOCTYPE HTML>
<html>
<head>
    <title>Hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
Hello
<a href="/hello">hello</a>
</body>
</html>

 

 

 

3. 프로젝트 실행 후, localhost:8080 접속

입력한 HTML 파일의 내용대로 Welcome Page가 생성되었습니다 ✨

저는 /hello에 만들어둔 페이지가 있어서 hello를 클릭하면 해당 페이지로 이동되네요

이런 방식은 정적 파일을 단지 연 것이기 때문에

프로그램을 열었다기 보다는 파일을 열었다고 볼 수 있습니다!

 

👉 템플릿을 사용하여 loop를 넣는 등의 동작을 수행할 수 있는 페이지를 Welcome page로 만들어봅시다!

 

 

 

 

 

 

 

> 템플릿 Welcome Page 만들기

 

0. thymeleaf 템플릿 엔진 관련 사이트

thymeleaf 공식 사이트 : 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

스프링 공식 튜토리얼 : https://spring.io/guides/gs/serving-web-content/

 

Serving Web Content with Spring MVC

this guide is designed to get you productive as quickly as possible and using the latest Spring project releases and techniques as recommended by the Spring team

spring.io

스프링 부트 메뉴얼 : https://docs.spring.io/spring-boot/docs/2.3.1.RELEASE/reference/html/spring-boot-features.html#boot-features-spring-mvc-template-engines

 

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

 

 

1. src > main > java > 프로젝트 에 패키지와 class 생성

controller 패키지와 Hellocontroller class를 생성했습니다.

 

 

2. 다음과 같은 코드를 입력합니다

spring에서는 컨트롤러를 생성할 때에는 @Controller 어노테이션을 꼭 추가해야 합니다!

package practice.springpractice.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";
    }
}

 

 

3. templates에 hello.html 파일을 생성하고 다음 코드를 입력합니다

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Hello</title>
    <meta http-equiv="Content-Type" charset="text/html; charset=UTF-8"/>
</head>
<body>
<p th:text="'안녕하세요. ' + ${data}" >안녕하세요. 손님</p>
</body>
</html>

둘째 줄에서의 선언으로 thymeleaf 문법을 사용할 수 있습니다

<p> 태그의 th는 thymeleaf를 나타냅니다

 

 

 

4. 실행

localhost:8080/hello

hello.html의 ${data} 부분에

java class에서 attributeValue로 지정해주었던 "hello!!''가 들어가 화면에 출력되었죠

 

 

 

5. 동작 환경 설명

- helloController

    - model의 data에 "hello!!"를 넣는다

    - return인 "hello"를 resources > templates에서 찾아서 랜더링한다 (hello.html)

- hello.html을 spring이 찾아서 Tymeleaf 템플릿 엔진이 처리해준다

 

- 컨트롤러에서 리턴 값으로 문자를 반환하면 뷰 리졸버(view resolver)가 화면을 찾아서 처리한다

    - 스프링 부트 템플릿엔진 기본 viewName 매핑

    - 'resource:templates/' + {ViewName} + '.html'

 

 

 

 

📌 참고 : 'spring-boot-devtools' 라이브러리를 추가하면, 'html' 파일을 컴파일만 해주면 서버 재시작 없이 View 파일 변경이 가능하다

인텔리J 컴파일 방법 : 메뉴 build -> Recompile

 

 

 

 

 

 

 

 

> Spring boot를 잘 사용하는 법

Spring boot는 Spring 전체를 커버하고 있고, Spring이 java application 생태계를 크게 차지하는 만큼

모든 것을 머릿속에 다 담을 수는 없습니다 😥

따라서 필요한 기능을 잘 찾아서 사용하는 능력이 중요하겠죠! 😤

지금 사용한 Welcome page 기능에 대해 알아보는 과정을 소개하겠습니다

 

1. spring.io 사이트 접속

 

 

2. Projects > Spring Boot

 

 

3. Learn > 현재 버전의 Reference Doc.

 

 

4. 원하는 기능 찾기

어떤 section에 있는지 안다면 좋겠지만, 모른다면 저처럼 a single HTML page를 클릭해서 검색하시면 편합니다!

a single HTML page
검색 결과

내용을 보니 먼저 static에서 index.html 파일을 찾고, 없다면 index template을 찾는다고 하네요

https://docs.spring.io/spring-boot/docs/current/reference/html/web.html#web.servlet.spring-mvc.welcome-page

 

 

 

 

 

 

 

 

 

 

 

 

이 포스팅은 스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술을 듣고 공부한 내용을 정리한 것입니다

 

[무료] 스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술 - 인프런 | 강의

스프링 입문자가 예제를 만들어가면서 스프링 웹 애플리케이션 개발 전반을 빠르게 학습할 수 있습니다., - 강의 소개 | 인프런...

www.inflearn.com

 

 

728x90