[SeSACx코딩온] Spring Boot와 Thymeleaf
Thymeleaf란?
- HTML과 서버 데이터를 결합하여 동적인 웹 페이지를 생성하는 템플릿 엔진입니다.
- 스프링 부트와 쉽게 통합되며, 데이터를 HTML 태그에 동적으로 바인딩할 수 있습니다.
1. Thymeleaf를 사용하기 위한 준비
1) 의존성 추가
Thymeleaf를 사용하려면 프로젝트에 spring-boot-starter-thymeleaf
의존성을 추가해야 합니다.
build.gradle
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
}
pom.xml
(Maven)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2) Thymeleaf 템플릿 경로
- Thymeleaf는 기본적으로
src/main/resources/templates
디렉토리에서 템플릿 파일을 찾습니다. - 컨트롤러에서 반환하는 문자열은 템플릿 파일 경로와 매칭됩니다.
예:return "_01_thymeleaf/hi"
→src/main/resources/templates/_01_thymeleaf/hi.html
템플릿 경로를 변경하려면 properties에서 경로 변경
spring.thymeleaf.prefix=classpath:/custom-templates/
spring.thymeleaf.suffix=.html
3) HTML 네임스페이스
HTML 파일에서 Thymeleaf를 사용하려면 네임스페이스 선언을 추가해야 합니다.
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
2. Controller 코드
@Controller
public class HelloController {
@GetMapping("/hi")
public String getHi(Model model) {
// 단일 데이터 전달
model.addAttribute("msg", "Hi~");
model.addAttribute("age", 30);
// 리스트 데이터 전달
List<String> names = Arrays.asList("kim", "lee", "park", "hong");
model.addAttribute("names", names);
// 객체 전달
Hello hello = new Hello(100);
model.addAttribute("classHello", hello);
return "_01_thymeleaf/hi"; // 템플릿 파일 경로 반환
}
}
class Hello {
private int age;
public Hello(int age) { this.age = age; }
public int getAge() { return age; }
}
3. Thymeleaf 템플릿 파일
<!doctype html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Thymeleaf 예제</title>
</head>
<body>
<!-- 단일 데이터 출력 -->
<p th:text="'안녕하세요. ' + ${msg}">기본 텍스트</p>
<p th:if="${age} < 20" th:text="'미성년자입니다. 나이: ' + ${age}"></p>
<p th:unless="${age} < 20" th:text="'성인입니다. 나이: ' + ${age}"></p>
<!-- 반복문 -->
<ul>
<li th:each="name : ${names}" th:text="${name}"></li>
</ul>
<!-- 객체 데이터 출력 -->
<div th:text="'Hello 클래스의 나이: ' + ${classHello.getAge()}"></div>
</body>
</html>
4. 실행 결과
1) URL 접근
- 브라우저에서
http://localhost:8080/hi
로 접속합니다.
2) 출력 결과
<p>안녕하세요. Hi~</p>
<p>성인입니다. 나이: 30</p>
<ul>
<li>kim</li>
<li>lee</li>
<li>park</li>
<li>hong</li>
</ul>
<div>Hello 클래스의 나이: 100</div>
5. Thymeleaf 문법과 기능
1) 데이터 출력 (th:text
, th:utext
)
th:text
: HTML 태그 안에 텍스트 데이터를 출력합니다.th:utext
: HTML 태그를 포함한 데이터를 그대로 렌더링합니다.
2) 조건문 (th:if
, th:unless
)
th:if
: 조건이 참일 때 요소를 렌더링합니다.th:unless
: 조건이 거짓일 때 요소를 렌더링합니다.
3) 반복문 (th:each
)
- 리스트 데이터를 순회하며 HTML 요소를 반복 출력합니다.
4) URL 처리 (th:href
, th:src
)
- 동적인 URL을 생성하거나 리소스 파일 경로를 설정할 때 사용합니다.
<a th:href="@{/hi}">링크</a>
<img th:src="@{/img/spring.png}" alt="스프링 이미지">