5. Thymeleaf 사용법
Thymeleaf 사용법
기존의 JSP에서 벗어나 템플릿 기반의 화면 처리가 지원된다. 따라서
FreeMarker , Mustache, Thymeleaf를 이용해 확장자가 html인 페이지를 개발할 수 있다.
Tymeleaf를 이용하기 위해 필요한 사항
별도의 라이브러리(STS4 에서 프로젝트 생성시에 추가하면 됨)
application.properties에 필요한 설정
이유 : Thymeleaf로 개발된 화면을 수정하면 매번 프로젝트를 재시작해야되기 때문에 서버 내부에 Cache 보관 못하게 끄자.
spring.thymeleaf.cache=false
Thymleaf는 html 파일에서 추가 해야될 것
<html xmlns:th="http://www.thymeleaf.org">
생략 ...
</html>
페이지 수정시에 DevTools 를 추가하고 쓰자
자동으로 스프링부트를 재시작 해주기때문에 사용함.
Thymeleaf 플러그인 설치하기
자체 기능을 사용하기 위해서는 템플릿 코드를 쓰면되지만 좀 더 편하게 활용하려면 추가 플러그인이 필요하다.
설치관련 사이트 : thymeleaf github
해당사이트에서 URL 을 보고 STS4 -> help -> install new softwares
New Repository -> name : thymeleaf , location : 사이트에 나옴 -> 라이센스 동의 -> reboot
Model 파라미터 전달법
thymeleaf 는 Controller에서 Model을 이용하여 attribute를 전달할 수 있다.
Controller
@GetMapping("/1") public void sample(Model model){ MemberVO vo = new MemberVO(p1,p2,p3); model.addAttribute("member",vo); }
View
<h1 th:text="${vo}"></h1>
each 문을 통해서 얻을 수 있는 점
<tr th:each="memeber : ${list}">
<td th:text="${member.mid}"></td>
</tr>
아래의 요소들 추가가능
<tr th:each="memeber, iterState : ${list}">
<td th:text="${member.mid}"></td>
<td th:text="${iterState.size}></td> // 대상의 size
<td th:text="${iterState.index}></td> // 대상의 인덱스번호
<td th:text="${iterState.odd or even}></td> // 짝 홀
<td th:text="${iterState.first or last}></td> // 첫번째 마지막
</tr>
Thymeleaf 의 유틸리티 객체
기본 표현식 객체
ctx
vars
locale
httpServletRequest
httpSession
표현식 유틸 객체
dates
calendars
numbers
strings
objects
bools
arrays
lists
sets
maps
aggregates
messages
유틸객체 사용법
Controller
model.addAttribute("now",new Date());
View
<h2 th:text="${#dates.format(now,'yyyy-mm-dd')}"></h2>
<div th:with="timeVal=${#dates.createToday()}">
<p>[[${timeVal}]]</p>
</div>
thymeleaf 링크 처리
WAS 상 경로를 줄때 '/'을 중심으로 둘 경우가 있기 때문에 문제가 발생할 수 있다.
Thymeleaf는 경로 처리문제를 해결하기 위해 @{} 을 사용한다. 장점은 현재경로를 기반으로 해서 일처리를 진행한다. 절대경로로 처리하고 싶으면 안에다가 절대경로를 지정해도 된다.
현재 경로 : /test
1. @{/sample1} => /test/sample1
2. @{~/sample1} => /sample1
현재 경로 : /
1. @{/sample1} => /sample1
2. @{~/sample1} => /sample1
Get 방식 파라미터 전달방법
@{/sample1(p1='aaa')} => /sample1?p1='aaa'
thymeleaf 레이아웃 기능
https://html5boilerplate.com/ 에서 레이아웃 재사용을 위한 탬플릿을 사용할 수 있음.
<!-- https://mvnrepository.com/artifact/nz.net.ultraq.thymeleaf/thymeleaf-layout-dialect -->
<dependency>
<groupId>nz.net.ultraq.thymeleaf</groupId>
<artifactId>thymeleaf-layout-dialect</artifactId>
<version>2.2.1</version>
</dependency>
Last updated
Was this helpful?