Notice
Recent Posts
Recent Comments
Link
삶의 공유
[Spring] Thymeleaf 사용법 - 실전 예제로 배우는 문법 정리 본문
728x90
반응형
Thymeleaf는 Spring Boot에서 가장 많이 쓰이는 템플릿 엔진입니다. HTML 문법을 그대로 유지하면서 서버 데이터를 동적으로 출력할 수 있어 프론트와 백엔드가 함께 개발할 때 매우 유용합니다.
이번 글에서는 아래 컨트롤러와 뷰 코드를 예시로 들어, Thymeleaf의 주요 기능들을 정리해 보겠습니다.
✅ 컨트롤러 예시 코드
@GetMapping("/test")
public String test(Model model, HttpServletRequest request){
request.setAttribute("year", 2022);
HttpSession session = request.getSession();
session.setAttribute("id", "asdf");
ServletContext application = session.getServletContext();
application.setAttribute("email", "service@asdf.com");
model.addAttribute("lastName", "AA");
model.addAttribute("firstName", "BB");
model.addAttribute("list", Arrays.asList("aaa", "bbb","ccc","ddd","eee"));
model.addAttribute("bno",123);
model.addAttribute("user", new User("aaa", 20));
return "test";
}
🔹 기본 표현식 출력
<h1 th:text="|year : ${year}|"></h1>
<h1 th:text="|id : ${session.id}|"></h1>
<h1 th:text="|email : ${application.email}|"></h1>
- ${year}: request scope에 저장된 값 출력
- ${session.id}: session에 저장된 값
- ${application.email}: ServletContext(application scope) 값
🔹 JavaScript에 값 주입
<script th:inline="javascript">
var firstName = [[${firstName}]];
var lastName = /*[[${lastName}]]*/ "testName";
var arr = [[${list}]];
var userObj = [[${user}]];
</script>
- [[...]]는 inline 표현식으로 HTML/JS에서 Thymeleaf 값을 사용할 수 있게 해줍니다.
- /*[[...]]*/는 JS 주석과 함께 사용할 수 있어 디버깅에도 유리합니다.
🔹 URL 동적 생성
<a th:href="@{/board/list(bno=${bno}, type='L')}">링크</a>
- @{...}는 URL을 동적으로 생성합니다.
- 파라미터도 ${}를 통해 바로 넣을 수 있어 유용합니다.
🔹 반복문 처리 (th:each)
<th:block th:each="opt : ${list}" >
<input type="checkbox" th:value="${opt}">[[${opt}]]<br>
</th:block>
<select multiple>
<option th:each="opt : ${list}" th:value="${opt}">[[${opt}]]</option>
</select>
<table border="1px">
<tr th:each="item : ${list}">
<td th:text="${item}"></td>
</tr>
</table>
- th:each는 Java의 향상된 for문처럼 리스트를 반복하며 요소를 출력합니다.
- <th:block> 태그는 실제로 렌더링되지 않는 그룹 태그로 반복 출력 시 유용합니다.
🔹 조건문 처리 (th:if)
<tr th:if="${#lists.size(list) == 0}">
<td>게시물이 없습니다.</td>
</tr>
- th:if를 통해 조건에 따라 HTML 요소를 출력할 수 있습니다.
- #lists.size()는 Thymeleaf 유틸 객체로 리스트의 크기를 반환합니다.
🔹 텍스트 출력 방식 비교
<h1 th:text="${lastName}">lastName</h1>
<h1>[[${firstName}]]</h1>
<h1 th:text="'My Name is' + ${lastName} + ', ' + ${firstName}">test</h1>
<h1 th:text="|My Name is ${lastName}, ${firstName}|"></h1>
- th:text: Escape 된 일반 텍스트 출력
- [[...]]: Inline 표현식, JS 또는 HTML 내에서 출력
- |...|: 템플릿 문자열처럼 사용
🔹 HTML 태그 출력 방식
<span th:text="${'<i>Song, Wongeun</i>'}"></span> <!-- 태그가 문자열로 출력됨 -->
<span th:utext="${'<i>Song, Wongeun</i>'}"></span> <!-- 태그가 HTML로 출력됨 -->
- th:text: HTML Escape가 기본 적용됨 (보안상 안전)
- th:utext: Escape 없이 raw HTML 그대로 렌더링됨 (주의 필요)
✨ 마무리
이번 예시를 통해 Thymeleaf에서 자주 사용하는 표현식과 기능들을 실전 코드로 살펴봤습니다.
템플릿 문법은 HTML과 거의 같기 때문에 백엔드 개발자도 직관적으로 사용할 수 있으며, Spring Boot와도 매우 자연스럽게 통합됩니다.
반응형
'Web Dev > BackEnd' 카테고리의 다른 글
[Spring] Java Reflection API: 런타임에 클래스를 조작하는 마법 (0) | 2025.04.18 |
---|---|
[Spring] Spring DI(Dependency Injection) 원리-1 (0) | 2025.04.17 |
HTTP 요청 방식 정리: 예시로 이해하는 GET, POST, Redirect, Forward (0) | 2025.04.15 |
[Spring] Filter와 Interceptor 완벽 정리: 개념과 예제로 이해 (0) | 2025.04.06 |
[Spring] Annotation@Mapping 역할 (0) | 2025.04.03 |