본문 바로가기
Programming/JAVA

[Spring boot] 3. 정적 페이지와 템플릿 페이지 띄워보기

by Berasix 2022. 12. 21.
반응형

1. 파일 추가하기

src > resources > static > index.html 파일을 만들어 본다.

<!DOCTYPE HTML>
<html>
<head>
    <title>Welcome</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
환영합니다.
<p><a href="/welcome">이동</a></p>
</body>
</html>

2. 빌드 및 실행

매우 잘 뜬다.

이는 스프링 부트가 제공하는 Welcome Page를 이용해 본 것이다.

아래 링크에서 Welcome Page에 대해 읽어보도록 하자.

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

 

Spring Boot Reference Documentation

This section goes into more detail about how you should use Spring Boot. It covers topics such as build systems, auto-configuration, and how to run your applications. We also cover some Spring Boot best practices. Although there is nothing particularly spe

docs.spring.io

 

3. Spring boot 대표 템플릿 엔진

FreeMaker, Groovy, Mustache, Thymeleaf

https://docs.spring.io/spring-boot/docs/3.0.0/reference/htmlsingle/#web.servlet.spring-mvc.template-engines

 

Spring Boot Reference Documentation

This section goes into more detail about how you should use Spring Boot. It covers topics such as build systems, auto-configuration, and how to run your applications. We also cover some Spring Boot best practices. Although there is nothing particularly spe

docs.spring.io

필자는 Thymeleaf를 사용하도록 하겠다.

 

4. Thymeleaf를 사용하기

1) Controller 만들기

controller라는 패키지를 만들고

방금 만든 controller 패키지에 아래와 같이 MainController java 파일을 하나 추가한다.

소스는 아래와 같다.

http://localhost:8080/main 페이지를 만들 것이다.

[ MainController.java ]

package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class MainController {
    @GetMapping("main")
    public String main(Model model) {
        model.addAttribute("data", "메인 페이지 입니다.");
        return "main";
    }
}

 

2) 템플릿 파일 만들기

resources/templates 폴더에 main.html 파일을 만들어준다.

소스는 아래와 같다

[ main.html ]

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Main 페이지</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'여기는 ' + ${data}" >페이지 소개</p>
</body>
</html>

 

3) 결과 확인

 

컨트롤러에서 리턴 값으로 문자를 반환하면 ( MainController.java 의 return "main"; )

viewResolver가 화면을 찾아서 처리한다. ( 즉, main.html 로 연결 )

 

 

이 글은 필자가 분석, 공부하면서 작성한 포스트입니다. 

잘못된 부분에 대해 알려주시면 수정하도록 하겠습니다.

728x90

댓글