본문 바로가기
SpringBoot/웹 애플리케이션 개발

템플릿 엔진(Thymeleaf) 연동

by DEVLIB 2025. 4. 14.
728x90

Thymeleaf란?

Thymeleaf는 HTML 파일에 서버 데이터를 바인딩하여 동적으로 화면을 구성할 수 있게 해주는 템플릿 엔진입니다.

특징 설명
HTML 문법을 그대로 유지 브라우저에서 템플릿 자체 미리보기 가능
서버-사이드 렌더링 @Controller와 함께 HTML 응답
Spring과 높은 호환성 spring-boot-starter-thymeleaf 제공

1. 의존성 추가

build.gradle 예시

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'org.springframework.boot:spring-boot-starter-web'
}

spring-boot-starter-thymeleaf가 HTML 템플릿 처리기를 자동으로 등록해 줍니다.


2. 폴더 구조 준비

Thymeleaf 템플릿 파일은 다음 위치에 있어야 합니다:

src/
└── main/
    └── resources/
        ├── templates/     ← .html 파일 위치
        └── static/        ← css, js, 이미지 등 정적 파일

3. 컨트롤러에서 HTML 렌더링

@Controller
public class HelloController {

    @GetMapping("/hello")
    public String hello(Model model) {
        model.addAttribute("name", "홍길동");
        return "hello"; // → templates/hello.html 렌더링
    }
}

4. Thymeleaf HTML 작성 (hello.html)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Welcome</title>
</head>
<body>
    <h1 th:text="'안녕하세요, ' + ${name} + '님!'">안녕하세요, 단비님!</h1>
</body>
</html>
 

th:text는 HTML 요소의 텍스트를 동적으로 설정해주는 Thymeleaf의 기본 속성 문법입니다.


주요 Thymeleaf 속성 정리

속성  설명 예시
th:text 텍스트 변경 <p th:text="${title}">제목</p>
th:href 링크 주소 <a th:href="@{/user}">이동</a>
th:if / th:unless 조건문 <div th:if="${user != null}">Welcome</div>
th:each 반복문 <li th:each="item : ${list}">[[${item}]]</li>
th:src 이미지 경로 <img th:src="@{/images/logo.png}"/>

5. 브라우저 테스트

Spring Boot 애플리케이션 실행 후,
http://localhost:8080/hello 접속 시

홍길동이라는 이름이 바인딩된 HTML 페이지가 보이게 됩니다.


마무리 요약

항목 내용
템플릿 엔진 Thymeleaf
목적 HTML 기반 웹 페이지를 서버에서 렌더링
위치 resources/templates/
컨트롤러 @Controller와 함께 사용
HTML에서 데이터 바인딩 th:text, th:each, th:if 등 활용
LIST

'SpringBoot > 웹 애플리케이션 개발' 카테고리의 다른 글

정적 리소스 처리  (0) 2025.04.14
컨트롤러(@RestController, @Controller)  (0) 2025.04.14