조건문 (if, unless)
Thymeleaf에서는 th:if와 th:unless를 사용하여 조건에 따라 HTML 요소를 동적으로 렌더링할 수 있다. th:if는 조건이 참일 때 태그를 렌더링하고, th:unless는 조건이 거짓일 때 렌더링한다.
■ Controller.java
model.addAttribute("age", 25);
model.addAttribute("movie", "모아나2");
model.addAttribute("today", "화요일");
■ ifcondition.html / 조건을 활용한 목록 표
<h3 th:text="'시청 불가'" th:if="${age < 19}"></h3>
<h3 th:text="'시청 불가'" th:if="${age lt 19}"></h3>
<h3 th:text="'시청 가능'" th:unless="${age > 19}"></h3><!-- 거짓 일 때 -->
결과 : 시청 가능
<ul th:if="${movie == '베놈'}"><!-- 조건이 참이면 ul 태그가 실행되고, 거짓이면 수행되지 않는다. -->
<li>글래디에이터</li>
<li>기자 - 에디블록</li>
<li>탑건</li>
</ul>
결과 : - 글래디에이터
- 기자 - 에디블록
- 탑건
<th:block th:if="${today == '수요일'}">
<h3>수요일은 빨간 장미를 받는 날</h3>
<h4>1주일의 가운데이다.</h4>
</th:block>
결과 : 수요일은 빨간 장미를 받는 날
1주일의 가운데이다.
반복
th:each
<table>
<tr>
<th>Count</th>
<th>Name</th>
<th>Age</th>
</tr>
<tr th:each="dto, dtoStat : ${list}"><!--/* list 반복 for(dto : PersonDTO) | <c:forEach var="dto" items="${list}"> */-->
<td th:text="${dtoStat.count}">1</td>
<td th:text="${dto.name}">name</td>
<td>
<span th:text="${dto.age}">0</span>
<span th:text="'성인'" th:if="${dto.age >= 19}"></span>
<span th:text="'청소년'" th:unless="${dto.age >= 19}"></span>
</td>
</tr>
</table>
이 예제는 list라는 객체 리스트를 반복하여 각 dto 항목을 출력한다.
또한, 나이에 따라 "성인" 또는 "청소년"을 동적으로 표시한다.
Switch
<table>
<tr>
<th>Count</th>
<th>Name</th>
<th>Age</th>
</tr>
<tr th:each="dto, dtoStat : ${list}"><!--/* list 반복 for(dto : PersonDTO) | <c:forEach var="dto" items="${list}"> */-->
<td th:text="${dtoStat.count}">1</td>
<td th:text="${dto.name}">name</td>
<td th:switch="${dto.age}">
<span th:case="25">20대</span>
<span th:case="17">10대</span>
<span th:case="*">30대 이상</span>
</td>
</tr>
</table>
이 예제는 나이에 따라 다른 범주(20대, 10대, 30대 이상)를 표시한다.
*는 기본값으로 다른 모든 경우를 처리한다.
기타
index = <span th:text="${dtoStat.index}"></span><br/>
count = <span th:text="${dtoStat.count}"></span><br/>
size = <span th:text="${dtoStat.size}"></span><br/>
even?짝 = <span th:text="${dtoStat.even}"></span><br/>
odd?홀 = <span th:text="${dtoStat.odd}"></span><br/>
first?첫번째 = <span th:text="${dtoStat.first}"></span><br/>
last?마지막 = <span th:text="${dtoStat.last}"></span><br/>
current데이터 = <span th:text="${dtoStat.current}"></span><br/>
기타 예제
block
<th:block th:each="dto : ${list}">
<div>
이름 : <span th:text="${dto.name}"></span>
나이 : <span th:text="${dto.age}"></span>
</div>
<div>
요약 : <span th:text="${dto.name} + ' / ' + ${dto.age}"></span>
</div>
</th:block>
Url 처리
Thymeleaf에서는 th:href 속성을 사용하여 URL을 동적으로 생성할 수 있다. 이때, 쿼리 파라미터를 동적으로 추가할 수도 있다.
<li><a th:href="@{/hello}">Basic URL</a></li>
//-> http://localhost:8080/hello
<li><a th:href="@{/hello(name=${'홍길동'}, age=${25})}">Query Param</a></li>
//-> http://localhost:8080/hello?name=홍길동&age=25
Query Param
■ Html
<li><a th:href="@{/hello(name=${'hong'}, age=${25})}">Query Param</a></li>
<li><a th:href="@{/hello(param1=${param1}, param2=${param2})}">Query Param</a></li>
@{} 구문을 사용하여 URL을 동적으로 생성하고, 쿼리 파라미터를 추가할 수 있다.
[에러문구]
There was an unexpected error (type=Internal Server Error, status=500).
Name for argument of type [java.lang.String] not specified, and parameter name information not available via reflection. Ensure that the compiler uses the '-parameters' flag.
[해결방법]
public String hello(@RequestParam("name") String name, @RequestParam("age") int age, Model model)
[에러문구]
There was an unexpected error (type=Bad Request, status=400).
Required parameter 'name' is not present.
org.springframework.web.bind.MissingServletRequestParameterException: Required request parameter 'name' for method parameter type String is not present
-> 데이터 에러
[해결방법]
defaultValue 주면 된다.
@RequestParam(name="name", defaultValue="noname") String name,
@RequestParam(name="age", defaultValue="0") int age,
■ Controller
@GetMapping(value="hello")
@ResponseBody
public String hello(@RequestParam(name="name", defaultValue="noname") String name,
@RequestParam(name="age", defaultValue="0") int age,
Model model) {
return name + " / " + age;
}
Path Variable
URL 경로의 변수도 th:href에서 동적으로 설정할 수 있습니다. 경로에 변수 값을 삽입하려면 {}를 사용한다.
■ Html
<li><a th:href="@{/hello/{name}/{age}(name=${'hong'}, age=${25})}">Path Variable</a></li>
//-> http://localhost:8080/hello/hong/25
■ Controller
public String hello2(@PathVariable(name="name") String name, @PathVariable(name="age") int age, Model model) {
Path Variable + Query Param
경로 변수와 쿼리 파라미터를 동시에 사용할 수도 있다.
■ Html
<li><a th:href="@{/hello3/{name}(name=${'hong'}, age=${25})}">Path Variable + Query Param</a></li>
■ controller.java
@GetMapping(value="hello3/{name}")
@ResponseBody
public String hello3(@PathVariable(name="name") String name, @RequestParam(name="age") int age, Model model) {
return name + " / " + age;
}
Spring Bean 사용하기
지역정보
<span th:text="${#locale}">
결과 : ko_KR
#locale => 현재 요청의 언어 및 지역 정보를 가져온다.
Param
<li>Request Parameter = <span th:text="${param.paramData}"></span></li>
<p><a href="basicobject">basicobject.html(파라메터 X)</a></p>
<p><a href="basicobject?paramData=Good">basicobject.html(파라메타 O)</a></p>
<li>spring bean = <span th:text="${@helloTest.hello('Spring Boot!')}"></span></li>
@{링크}가 아니다. ${@ } -> 스프링 bean을 참조한다.
스프링 애플리케이션 컨텍스트에 등록한 빈의 이름이다.
@Component, @Service, @Repository, ... 등 어노테이션을 사용하여 빈으로 생성된다.
helloTest 빈의 hello 메서드를 호출하고, 결과를 템플릿에 출력한다.
날짜 및 시간 처리
Controller
model.addAttribute("startTime", startTime);
startTime 값을 저장했을 때
출력방식
Thymeleaf는 #dates, #temporals, #calendars와 같은 유틸리티 객체를 제공하여 날짜 및 시간을 포맷팅할 수 있다.
#temporals
[[${startTime}]]
[[${#temporals.format(startTime, 'yyyy-MM-dd HH:mm:ss')}]]
[[${#temporals.format(startTime, 'yyyy년 MM월 dd일 HH시 mm분 ss초')}]]
#dates
[[${#dates}]]
[[${#dates.createNow()}]]
[[${#dates.format(#dates.createNow(), 'YYYY/MM/DD HH:mm')}]]
[[${#dates.format(#dates.createNow(), 'yyyy년 MMM d일')}]]
[[${#dates.format(#dates.createNow(), 'hh:mm:ss')}]]
[[${#dates.format(#dates.createNow(), 'ddd dd d')}]]
[[${#calendars.dayOfWeekName(#dates.createNow())}]]
기타
문자열 출력 방식
[[${#strings}]]
[[${#strings.isEmpty(param.name)}]]
[[${#strings.isEmpty(startTime)}]]
[[${#strings.isEmpty(str)}]]
[[${#strings.length(str)}]]
'[[${#strings.toLowerCase(str)}]]'
'[[${str}]]'
'[[${#strings.trim(str)}]]'
#strings.isEmpty() 메서드는 문자열이 비었는지 (빈 문자열 또는 null인지) 확인
#strings.length() 메서드는 문자열의 길이를 반환
#strings.toLowerCase() 메서드는 문자열을 모두 소문자로 변환
#strings.trim() 메서드는 문자열의 양쪽 공백을 제거
숫자 변형
${num}
${#numbers.formatInteger(num, 3, 'COMMA')}
${#numbers.formatCurrency(num)}
${#numbers.formatDecimal(num, 3, 'COMMA', 2, 'POINT')}
param 객체 사용
param 객체는 HTTP 요청의 파라미터를 다룰 수 있는 기능을 제공한다. 이를 통해 클라이언트가 요청한 URL의 파라미터 값에 접근할 수 있다. 주로 GET 요청에서 URL에 포함된 쿼리 파라미터를 가져올 때 사용한다.
[[${param}]]
[[${param.size()}]]
[[${param.isEmpty()}]]
session 객체 사용
session 객체는 HTTP 세션에서 데이터를 다룰 수 있는 기능을 제공한다. 세션에 저장된 값에 접근하거나 세션 정보를 확인하는 데 유용하다.
[[${session}]]
[[${session.memId}]]
[[${session.size()}]]
[[${session.isEmpty()}]]
[[${session.keySet()}]]
- session.size()는 세션에 저장된 항목의 개수를 반환
- session.isEmpty()는 세션이 비어 있는지 여부를 체크
fragment
Thymeleaf에서는 여러 HTML 파일 간에 공통된 레이아웃을 재사용할 수 있도록 th:insert와 th:replace를 제공한다. 이를 통해 헤더, 푸터 등의 공통 부분을 재사용할 수 있다.
header
<div th:fragment="header">
<a href="">스프링페이지</a>
<a href=""> 타임리프 페이지</a>
</div>
info
<div th:fragment="info">
문의 사항은 admin@java.com 메일로 보내세요
</div>
footer
<footer th:fragment="foot(styles)" th:attr="style=${styles}">FOTTE PLACE</footer>
<footer th:fragment="footParam(param1, param2, styles)" th:attr="style=${styles}">
<p>FOOTPARAM PLACE</p>
<p th:text="${param1}"></p>
<p th:text="${param2}"></p>
</footer>
Total
<header th:insert="basic/fragment/menu :: header">여기는 menu</header>
<section>
여기는 fragmentMain1.html 페이지 입니다.
</section>
<footer th:insert="basic/fragment/info :: info">여기는 info</footer>
th:insert는 다른 HTML 팡리의 특정 프래그먼트를 현재 문서에 삽입
"basic/fragment/menu :: header"는 basic/fragment/menu.html 파일의 header라는 이름의 프레그먼트를 삽입하라는 의미
부분 포함 테스트
부분 포함 insert
<div th:insert="~{basic/fragment/footer :: foot('color:red;')}"></div>
부분 포함 replace
<div th:replace="~{basic/fragment/footer :: foot('color:blue;')}"></div>
부분 포함 단순 표현식
<div th:insert="basic/fragment/footer :: foot('color:magenta;')"></div>
파라미터 사용
<div th:replace="~{basic/fragment/footer :: footParam('데이터1', '데이터2', 'color : green;')}"></div>
<div th:replace="basic/fragment/footer :: footParam('데이터1', '데이터2', 'color : green;')"></div>
~{}는 타임리프에서 리소스의 상대 경로를 지정할 때 사용되는 구문이다.
'Spring' 카테고리의 다른 글
Spring Boot, Swagger란? (0) | 2025.02.25 |
---|---|
Sprint Boot, Sprint Boot + MyBatis (0) | 2024.11.14 |
Spring Boot, Thymeleaf 예제 -1 (0) | 2024.11.12 |
Spring Boot, Thymeleaf 란? (0) | 2024.11.12 |
Spring Boot, React와 같이 작업하기 (0) | 2024.11.11 |