[java] 스프링 부트에서 Thymeleaf 템플릿 사용하기

스프링 부트는 웹 애플리케이션 개발을 위한 다양한 기능을 제공하며 Thymeleaf 템플릿 엔진을 기본으로 제공합니다. Thymeleaf를 사용하면 서버측에서 동적인 웹 페이지를 손쉽게 생성할 수 있습니다. 이번 튜토리얼에서는 스프링 부트 애플리케이션에서 Thymeleaf를 사용하는 방법에 대해 알아보겠습니다.

스프링 부트 프로젝트 설정

먼저, 스프링 부트 프로젝트를 생성합니다. 이때, Maven이나 Gradle을 사용하여 프로젝트를 초기화합니다. 다음은 Maven을 사용하는 경우의 예시입니다.

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
</dependencies>

의존성을 추가하여 Thymeleaf를 프로젝트에 포함시킵니다.

Thymeleaf 템플릿 작성

Thymeleaf 템플릿은 HTML 파일 내에 Thymeleaf의 문법을 사용하여 작성됩니다. 다음은 간단한 Thymeleaf 템플릿의 예시입니다.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>환영합니다</title>
</head>
<body>
    <h1 th:text="${message}">환영합니다</h1>
</body>
</html>

위의 예시에서는 th:text 속성을 사용하여 변수 message의 값을 화면에 출력하는 방법을 보여줍니다.

컨트롤러에서 모델 데이터 전달

스프링 부트 컨트롤러 클래스에서 Thymeleaf 템플릿에 전달할 모델 데이터를 설정합니다.

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

@Controller
public class HomeController {

    @GetMapping("/")
    public String home(Model model) {
        model.addAttribute("message", "안녕하세요!");
        return "welcome"; // welcome.html로 이동
    }
}

위의 코드는 home 메소드에서 Thymeleaf 템플릿에 message라는 변수를 전달하는 예시입니다.

애플리케이션 실행

이제 스프링 부트 애플리케이션을 실행하고 http://localhost:8080/을 열면 Thymeleaf 템플릿이 적용된 화면을 볼 수 있습니다.

이렇게 스프링 부트에서 Thymeleaf를 사용하여 동적인 웹 페이지를 생성할 수 있습니다. Thymeleaf의 강력한 표현력과 스프링 부트의 편리한 기능을 함께 사용하여 웹 애플리케이션을 개발할 수 있습니다.