- Spring mvc2 타임리프 기본기능
- Spring mvc2 타임리프 스프링 통합과 폼
- Spring mvc2(2) 메세지, 국제화
- Spring mvc2(3) 검증1 validation
- Spring mvc2 검증2 1 bean validation
- Spring mvc2 검증2 2 로그인 처리1 쿠키, 세션
- Spring mvc2 검증2 3 로그인 처리2 필터, 인터셉터
- Spring mvc2 검증2 4 예외 처리와 오류 페이지
- Spring mvc2(1) api 예외처리
- Spring mvc2(2) 스프링 타입 컨버터
- Spring mvc2(3) 파일 업로드
Spring mvc2 타임리프 기본기능
0. 타임리프 기본 표현식
-
간단한 표현: ◦ 변수 표현식: ${...} ◦ 선택 변수 표현식: *{...} ◦ 메시지 표현식: #{...} ◦ 링크 URL 표현식: @{...} ◦ 조각 표현식: ~{...} • 리터럴 ◦ 텍스트: 'one text', 'Another one!',… ◦ 숫자: 0, 34, 3.0, 12.3,… ◦ 불린: true, false ◦ 널: null ◦ 리터럴 토큰: one, sometext, main,… • 문자 연산: ◦ 문자 합치기: + ◦ 리터럴 대체: |The name is ${name}| • 산술 연산: ◦ Binary operators: +, -, *, /, % ◦ Minus sign (unary operator): - • 불린 연산: ◦ Binary operators: and, or ◦ Boolean negation (unary operator): !, not • 비교와 동등: ◦ 비교: >, <, >=, <= (gt, lt, ge, le) ◦ 동등 연산: ==, != (eq, ne) • 조건 연산: ◦ If-then: (if) ? (then) ◦ If-then-else: (if) ? (then) : (else) ◦ Default: (value) ?: (defaultvalue) • 특별한 토큰: ◦ No-Operation: _
- 참고 : https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#standardexpression-syntax
1. 텍스트 - text, utext
텍스트 종류
th:text
<span th:text="${data}">
컨텐츠 안에서 직접 출력하기 = [[${data}]]
- th:utext (unescaped)
- ```
컨텐츠 안에서 직접 출력하기 = [(${data})]
BasicController
-
package hello.thymeleaf.basic; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller @RequestMapping("/basic") public class BasicController { @GetMapping("/text-basic") public String textBasic(Model model){ model.addAttribute("data", "Hello Spring"); return "basic/text-basic"; } @GetMapping("/text-unescaped") public String textUnescaped(Model model){ model.addAttribute("data", "Hello <b>Spring</b>"); return "basic/text-unescaped"; } }
- unescaped 에는 태그를 붙였다.
text-basic.html
-
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>컨텐츠에 데이터 출력하기</h1> <ul> <li>th:text 사용 <span th:text="${data}"></span></li> <li>컨텐츠 안에서 직접 출력하기 = [[${data}]]</li> </ul> </body> </html>
Escape
- HTML 문서는 < , > 같은 특수 문자를 기반으로 정의된다. 따라서 뷰 템플릿으로 HTML 화면을 생성할 때는 출력하는 데이터에 이러한 특수 문자가 있는 것을 주의해서 사용해야 한다.
- 테그를 사용해서 Spring!이라는 단어가 진하게 나오도록 하려면 utext 를 사용해야 한다.
- 그렇지 않으면 \<b> ; Spring! ! < ;/b> ; 처럼 나온다.
- 소스보기를 하면 < 부분이 < 로 변경된 것을 확인할 수 있다.
HTML 엔티티
- 웹 브라우저는 < 를 HTML 테그의 시작으로 인식한다. 따라서 < 를 테그의 시작이 아니라 문자로 표현할 수 있는 방법이 필요한데, 이것을 HTML 엔티티라 한다.
- 그리고 이렇게 HTML에서 사용하는 특수 문자를 HTML 엔티티로 변경하는 것을 이스케이프(escape)라 한다.
Unescape
-
이스케이프 기능을 사용하지 않기 위해 타임리프는 두 기능을 제공한다.
- th:text -> th:utext
- [[…]] -> [(…)]
-
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>text vs utext</h1> <ul> <li>th:text = <span th:text="${data}"></span></li> <li>th:utext = <span th:utext="${data}"></span></li> </ul> <h1><span th:inline="none">[[...]] vs [(...)]</span></h1> <ul> <li><span th:inline="none">[[...]] = </span>[[${data}]]</li> <li><span th:inline="none">[(...)] = </span>[(${data})]</li> </ul> </body> </html>
2. 변수 - SpringEL
- 변수 표현식 :
${...}
Controller
-
@GetMapping("/variable") public String variable(Model model){ User userA = new User("userA", 10); User userB = new User("userBA", 20); List<Object> list = new ArrayList<>(); list.add(userA); list.add(userB); Map<String, User> map = new HashMap<>(); map.put("userA", userA); map.put("userB", userB); model.addAttribute("user", userA); model.addAttribute("users", list); model.addAttribute("userMap", map); return "basic/variable"; }
- User, List, Map 을 만들어준다.
html 탬플릿
-
/resources/templates/basic/variable.html
-
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>SpringEL 표현식</h1> <ul>Object <li>${user.username} = <span th:text="${user.username}"></span></li> <li>${user['username']} = <span th:text="${user['username']}"></span></li> <li>${user.getUsername()} = <span th:text="${user.getUsername()}"></span></li> </ul> <ul>List <li>${users[0].username} = <span th:text="${users[0].username}"></span></li> <li>${users[0]['username']} = <span th:text="${users[0]['username']}"></span></li> <li>${users[0].getUsername()} = <span th:text="${users[0].getUsername()}"></span></li> </ul> <ul>Map <li>${userMap['userA'].username} = <span th:text="${userMap['userA'].username}"></span></li> <li>${userMap['userA']['username']} = <span th:text="${userMap['userA']['username']}"></span></li> <li>${userMap['userA'].getUsername()} = <span th:text="${userMap['userA'].getUsername()}"></span></li> </ul> </body> </html>
- Object
- user.username / user[‘username’] / user.getUsername() 등으로 접근가능하다
- List
- users[0] 으로 User 를 찾고, 이후에는 Object 와 똑같다.
- Map
- userMap[‘userA’] 로 User 를 찾고, 이후에는 Object 와 똑같다.
지역 변수 선언
-
th:with 를 사용하면 지역 변수를 선언해서 사용할 수 있다. 지역 변수는 선언한 테그 안에서만 사용할 수 있다.
-
<h1>지역 변수 - (th:with)</h1> <!--선언한 태그 안에서만 쓸 수 있음--> <div th:with="first=${users[0]}"> <p>처음 사람의 이름은 <span th:text="${first.username}"></span></p> </div>
3. 기본 객체들
- html 문서에서 request, response, session, servletContext, locale 등 제공
- springboot 3.0 이상에서는 ${#request} , ${#response} , ${#session} , ${#servletContext} 를 지원하지 않는다.
BasicController 추가
-
@GetMapping("/basic-objects") public String basicObjects(Model model, HttpServletRequest request, HttpServletResponse response, HttpSession session) { session.setAttribute("sessionData", "Hello Session"); model.addAttribute("request", request); model.addAttribute("response", response); model.addAttribute("servletContext", request.getServletContext()); return "basic/basic-objects"; } @Component("helloBean") static class HelloBean{ public String hello(String data){ return "Hello " + data; } }
- session, request, response, servletContext 는 Session 이나 model 에 set, addAttribute 를 통해 넣어줘야 한다.
basic-objects.html
-
/resources/templates/basic/basic-objects.html
-
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>식 기본 객체 (Expression Basic Objects)</h1> <ul> <li>request = <span th:text="${request}"></span></li> <li>response = <span th:text="${response}"></span></li> <li>session = <span th:text="${session}"></span></li> <li>servletContext = <span th:text="${servletContext}"></span></li> <li>locale = <span th:text="${#locale}"></span></li> </ul> <h1>편의 객체</h1> <ul> <li>Request Parameter = <span th:text="${param.paramData}"></span></li> <li>session = <span th:text="${session.sessionData}"></span></li> <li>spring bean = <span th:text="${@helloBean.hello('Spring!')}"></span></li> </ul> </body> </html>
- locale 정보는
"${#locale}"
로 바로 볼 수 있다. - 쿼리파라미터는 “${param.xxx}” 로 볼 수 있다.
- session 내용은 “${session.xxx}” 로 볼 수 있다. 이때 컨트롤러처럼 Session session.setAttibute(“name”, data) 로 설정해줘야 한다.
- 스프링 빈 접근은 앞에 @를 붙여주면 된다.
- 예) ${@helloBean.hello(‘Spring!’)}
- locale 정보는
4. 유틸리티 객체와 날짜
- 타임리프는 문자, 숫자, 날짜, URI등을 편리하게 다루는 다양한 유틸리티 객체들을 제공한다.
- 타임리프 유틸리티 객체 :
https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#expression-utility-objects
- 유틸리티 객체 예시 :
https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#appendix-b-expression-utility-objects
자바 날짜
BasicController 추가
-
@GetMapping("/date") public String date(Model model){ model.addAttribute("localDateTime", LocalDateTime.now()); return "basic/date"; }
/date.html
-
/resources/templates/basic/date.html
-
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>LocalDateTime</h1> <ul> <li>default = <span th:text="${localDateTime}"></span></li> <li>yyyy-MM-dd HH:mm:ss = <span th:text="${#temporals.format(localDateTime, 'yyyy-MM-dd HH:mm:ss')}"></span></li> </ul> <h1>LocalDateTime - Utils</h1> <ul> <li>${#temporals.day(localDateTime)} = <span th:text="${#temporals.day(localDateTime)}"></span></li> <li>${#temporals.month(localDateTime)} = <span th:text="${#temporals.month(localDateTime)}"></span></li> <li>${#temporals.monthName(localDateTime)} = <span th:text="${#temporals.monthName(localDateTime)}"></span></li> <li>${#temporals.monthNameShort(localDateTime)} = <span th:text="${#temporals.monthNameShort(localDateTime)}"></span></li> <li>${#temporals.year(localDateTime)} = <span th:text="${#temporals.year(localDateTime)}"></span></li> <li>${#temporals.dayOfWeek(localDateTime)} = <span th:text="${#temporals.dayOfWeek(localDateTime)}"></span></li> <li>${#temporals.dayOfWeekName(localDateTime)} = <span th:text="${#temporals.dayOfWeekName(localDateTime)}"></span></li> <li>${#temporals.dayOfWeekNameShort(localDateTime)} = <span th:text="${#temporals.dayOfWeekNameShort(localDateTime)}"></span></li> <li>${#temporals.hour(localDateTime)} = <span th:text="${#temporals.hour(localDateTime)}"></span></li> <li>${#temporals.minute(localDateTime)} = <span th:text="${#temporals.minute(localDateTime)}"></span></li> <li>${#temporals.second(localDateTime)} = <span th:text="${#temporals.second(localDateTime)}"></span></li> <li>${#temporals.nanosecond(localDateTime)} = <span th:text="${#temporals.nanosecond(localDateTime)}"></span></li> </ul> </body> </html>
5. URL 링크 생성
- 타임리프에서 URL을 생성할 때는 @{…} 문법을 사용하면 된다.
BasicController 추가
-
@GetMapping("/link") public String link(Model model){ model.addAttribute("param1", "data1"); model.addAttribute("param2", "data2"); return "basic/link"; }
/link.html
-
/resources/templates/basic/link.html
-
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>URL 링크</h1> <ul> <li><a th:href="@{/hello}">basic url</a></li> <li><a th:href="@{/hello(param1=${param1}, param2=${param2})}">hello query param</a></li> <li><a th:href="@{/hello/{param1}/{param2}(param1=${param1}, param2=${param2})}">path variable</a></li> <li><a th:href="@{/hello/{param1}(param1=${param1}, param2=${param2})}">path variable + query parameter</a></li> </ul> </body> </html>
-
@{/hello} :
http://localhost:8080/hello
-
@{/hello(param1=${param1}, param2=${param2})} :
http://localhost:8080/hello?param1=data1¶m2=data2
- () 에 있는 부분은 쿼리 파라미터로 처리된다
-
@{/hello/{param1}/{param2}(param1=${param1}, param2=${param2})} :
http://localhost:8080/hello/data1/data2
- URL 경로상에 변수가 있으면 () 부분은 경로 변수로 처리된다.
-
@{/hello/{param1}(param1=${param1}, param2=${param2})} :
http://localhost:8080/hello/data1?param2=data2
- 경로 변수와 쿼리 파라미터를 함께 사용할 수 있다.
6. 리터럴 대체 문법
-
리터럴은 소스 코드상에 고정된 값을 말하는 용어이다.
-
예를 들어서 다음 코드에서 “Hello” 는 문자 리터럴, 10 , 20 는 숫자 리터럴이다.
-
String a = "Hello" int a = 10 * 20
- 타임리프에서 문자 리터럴은 항상 ‘ (작은 따옴표)로 감싸야 한다.
<span th:text="'hello'">
- . 공백 없이 쭉 이어진다면 하나의 의미있는 토큰으로 인지해서 다음과 같이 작은 따옴표를 생략할 수 있다.
- 중간에 공백이 있어서 하나의 의미있는 토큰으로도 인식되지 않는다. :
<span th:text="hello world!"></span>
BasicController 추가
-
@GetMapping("/literal") public String literal(Model model){ model.addAttribute("data", "Spring!"); return "/basic/literal"; }
literal.html
-
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>리터럴</h1> <ul> <!--주의! 다음 주석을 풀면 예외가 발생함--> <!-- <li>"hello world!" = <span th:text="hello world!"></span></li>--> <li>'hello' + ' world!' = <span th:text="'hello' + ' world!'"></span></li> <li>'hello world!' = <span th:text="'hello world!'"></span></li> <li>'hello ' + ${data} = <span th:text="'hello ' + ${data}"></span></li> <li>리터럴 대체 |hello ${data}| = <span th:text="|hello ${data}|"></span></li> </ul> </body> </html>
- 리터럴 대체(Literal substitutions)
<span th:text="|hello ${data}|">
- 마지막의 리터럴 대체 문법을 사용하면 마치 템플릿을 사용하는 것 처럼 편리하다.
7. 연산
- HTML안에서 사용하기 때문에 HTML 엔티티를 사용하는 부분만 주의하면 된다.
BasicController 추가
-
@GetMapping("/operation") public String operation(Model model){ model.addAttribute("nullData", null); model.addAttribute("data", "Spring!"); return "/basic/operation"; }
operation.html
-
/resources/templates/basic/operation.html
-
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <ul> <li>산술 연산 <ul> <li>10 + 2 = <span th:text="10 + 2"></span></li> <li>10 % 2 == 0 = <span th:text="10 % 2 == 0"></span></li> </ul> </li> <li>비교 연산 <ul> <li>1 > 10 = <span th:text="1 > 10"></span></li> <li>1 gt 10 = <span th:text="1 gt 10"></span></li> <li>1 >= 10 = <span th:text="1 >= 10"></span></li> <li>1 ge 10 = <span th:text="1 ge 10"></span></li> <li>1 == 10 = <span th:text="1 == 10"></span></li> <li>1 != 10 = <span th:text="1 != 10"></span></li> </ul> </li> <li>조건식 <ul> <li>(10 % 2 == 0)? '짝수':'홀수' = <span th:text="(10 % 2 == 0)?'짝수':'홀수'"></span></li> </ul> </li> <li>Elvis 연산자 <ul> <li>${data}?: '데이터가 없습니다.' = <span th:text="${data}?: '데이터가없습니다.'"></span></li> <li>${nullData}?: '데이터가 없습니다.' = <span th:text="${nullData}?:'데이터가 없습니다.'"></span></li> </ul> </li> <li>No-Operation <ul> <li>${data}?: _ = <span th:text="${data}?: _">데이터가 없습니다.</span></li> <li>${nullData}?: _ = <span th:text="${nullData}?: _">데이터가없습니다.</span></li> </ul> </li> </ul> </body> </html>
- 비교연산: HTML 엔티티를 사용해야 하는 부분을 주의하자, > (gt), < (lt), >= (ge), <= (le), ! (not), == (eq), != (neq, ne)
- 조건식: 자바의 조건식과 유사하다.
- Elvis 연산자 : 조건식의 편의 버전, 조건이 맞으면 왼쪽 데이터 출력, 만족하지 않으면
-
가 출력된다. 엘비스를 닮아서 엘비스 연산자다. - No-Operation : 인 경우 마치 타임리프가 실행되지 않는 것 처럼 동작한다. 이것을 잘 사용하면 HTML 의 내용 그대로 활용할 수 있다.
8. 속성 값 설정(타임리프 태그 속성(Attribute))
- 타임리프는 주로 HTML 태그에 th:* 속성을 지정하는 방식으로 동작한다.
- th:* 로 속성을 적용하면 기존 속성을 대체한다.
- 기존 속성이 없으면 새로 만든다.
BasicController 추가
-
@GetMapping("/attribute") public String attribute(){ return "basic/attribute"; }
attribute.html
-
/resources/templates/basic/attribute.html
-
```html <!DOCTYPE html>
Title 속성 설정
속성 추가
- th:attrappend =
- th:attrprepend =
- th:classappend =
checked 처리
- checked o
- checked x
- checked=false
</body> </html> ```
- th:attrappend =
결과
- HTML
-
html 코드
- ```html
<!DOCTYPE html>
Title 속성 설정
속성 추가
- th:attrappend =
- th:attrprepend =
- th:classappend =
checked 처리
- checked o
- checked x
- checked=false
</body> </html> ```
- th:attrappend =
- ```html
<!DOCTYPE html>
- 속성 설정
- th:* 속성을 지정하면 타임리프는 기존 속성을 th:* 로 지정한 속성으로 대체한다. 기존 속성이 없다면 새로 만든다.
<input type="text" name="mock" th:name="userA" />
- 렌더링 후 :
<input type="text" name="userA" />
- 렌더링 후 :
- 속성 추가
- th:attrappend : 속성 값의 뒤에 값을 추가한다. (띄워쓰기가 되어있어야 한다.)
- th:attrprepend : 속성 값의 앞에 값을 추가한다. (띄워쓰기가 되어있어야 한다.)
- th:classappend : class 속성에 자연스럽게 추가한다.
- checked 처리
- HTML에서는
<input type="checkbox" name="active" checked="false" />
-> 이 경우에도 checked 속성이 있기 때문에 checked 처리가 되어버린다. - HTML에서 checked 속성은 checked 속성의 값과 상관없이 checked 라는 속성만 있어도 체크가 된다. 이런 부분이 true , false 값을 주로 사용하는 개발자 입장에서는 불편하다.
- 타임리프의 th:checked 는 값이 false 인 경우 checked 속성 자체를 제거한다.
<input type="checkbox" name="active" th:checked="false" />
- 렌더링 후 :
<input type="checkbox" name="active" />
- HTML에서는
9. 반복
- 타임리프에서 반복은 th:each 를 사용한다.
BasicController 추가
-
addUsers 로 model 에 정보 주입
-
@GetMapping("/each") public String each(Model model){ addUsers(model); return "/basic/each"; } private void addUsers(Model model){ List<User> list = new ArrayList<>(); list.add(new User("UserA", 10)); list.add(new User("UserB", 20)); list.add(new User("UserC", 30)); model.addAttribute("users", list); }
each.html
-
/resources/templates/basic/each.html
-
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>기본 테이블</h1> <table border="1"> <tr> <th>username</th> <th>age</th> </tr> <tr th:each="user : ${users}"> <td th:text="${user.username}">username</td> <td th:text="${user.age}">0</td> </tr> </table> <h1>반복 상태 유지</h1> <table border="1"> <tr> <th>count</th> <th>username</th> <th>age</th> <th>etc</th> </tr> <tr th:each="user, userStat : ${users}"> <td th:text="${userStat.count}">username</td> <td th:text="${user.username}">username</td> <td th:text="${user.age}">0</td> <td> index = <span th:text="${userStat.index}"></span> count = <span th:text="${userStat.count}"></span> size = <span th:text="${userStat.size}"></span> even? = <span th:text="${userStat.even}"></span> odd? = <span th:text="${userStat.odd}"></span> first? = <span th:text="${userStat.first}"></span> last? = <span th:text="${userStat.last}"></span> current = <span th:text="${userStat.current}"></span> </td> </tr> </table> </body> </html>
반복 기능
<tr th:each="user : ${users}">
:반복시 오른쪽 컬렉션( ${users} )의 값을 하나씩 꺼내서 왼쪽 변수( user )에 담아서 태그를 반복 실행한다.
반복 상태 유지
<tr th:each="user, userStat : ${users}">
- 반복의 두번째 파라미터를 설정해서 반복의 상태를 확인 할 수 있다
- 두번째 파라미터는 생략 가능한데, 생략하면 지정한 변수명( user ) + Stat 가 된다. 여기서는 user + Stat = userStat 이므로 생략 가능하다.
반복 상태 유지 기능
- index : 0부터 시작하는 값
- count : 1부터 시작하는 값
- ize : 전체 사이즈
- even , odd : 홀수, 짝수 여부( boolean )
- irst , last :처음, 마지막 여부( boolean )
- current : 현재 객체
렌더링 페이지
10. 조건부 평가
- 타임리프의 조건식 if , unless
BasicController 추가
-
@GetMapping("/condition") public String condition(Model model){ addUsers(model); return "basic/condition"; }
condition.html
-
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>if, unless</h1> <table border="1"> <tr> <th>count</th> <th>username</th> <th>age</th> </tr> <tr th:each="user, userStat : ${users}"> <td th:text="${userStat.count}">1</td> <td th:text="${user.username}">username</td> <td> <span th:text="${user.age}">0</span> <span th:text="'미성년자'" th:if="${user.age lt 20}"></span> <span th:text="'미성년자'" th:unless="${user.age ge 20}"></span> </td> </tr> </table> <h1>switch</h1> <table border="1"> <tr> <th>count</th> <th>username</th> <th>age</th> </tr> <tr th:each="user, userStat : ${users}"> <td th:text="${userStat.count}">1</td> <td th:text="${user.username}">username</td> <td th:switch="${user.age}"> <span th:case="10">10살</span> <span th:case="20">20살</span> <span th:case="*">기타</span> </td> </tr> </table> </body> </html>
렌더링된 코드 및 페이
-
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>if, unless</h1> <table border="1"> <tr> <th>count</th> <th>username</th> <th>age</th> </tr> <tr> <td>1</td> <td>UserA</td> <td> <span>10</span> <span>미성년자</span> <span>미성년자</span> </td> </tr> <tr> <td>2</td> <td>UserB</td> <td> <span>20</span> </td> </tr> <tr> <td>3</td> <td>UserC</td> <td> <span>30</span> </td> </tr> </table> <h1>switch</h1> <table border="1"> <tr> <th>count</th> <th>username</th> <th>age</th> </tr> <tr> <td>1</td> <td>UserA</td> <td> <span>10살</span> </td> </tr> <tr> <td>2</td> <td>UserB</td> <td> <span>20살</span> </td> </tr> <tr> <td>3</td> <td>UserC</td> <td> <span>기타</span> </td> </tr> </table> </body> </html>
- if, unless : 임리프는 해당 조건이 맞지 않으면 태그 자체를 렌더링하지 않는다
- 만약 다음 조건이 false 인 경우
<span>...</span>
부분 자체가 렌더링 되지 않고 사라진다.<span th:text="'미성년자'" th:if="${user.age lt 20}"></span>
- switch : 해당 th:case 에 맞으면 출력하고,
*
은 만족하는 조건이 없을 때 사용하는 디폴트이다.
11. 타임리프 주석
BasicController 추가
-
@GetMapping("/comments") public String comments(Model model) { model.addAttribute("data", "Spring!"); return "basic/comments"; }
comments.html
-
/resources/templates/basic/comments.html
-
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>예시</h1> <span th:text="${data}">html data</span> <h1>1. 표준 HTML 주석</h1> <!-- <span th:text="${data}">html data</span> --> <h1>2. 타임리프 파서 주석</h1> <!--/* [[${data}]] */--> <!--/*--> <span th:text="${data}">html data</span> <!--*/--> <h1>3. 타임리프 프로토타입 주석</h1> <!--/*/ <span th:text="${data}">html data</span> /*/--> </body> </html> 결과 <h1>예시</h1> <span>Spring!</span> <h1>1. 표준 HTML 주석</h1> <!-- <span th:text="${data}">html data</span> --> <h1>2. 타임리프 파서 주석</h1> <h1>3. 타임리프 프로토타입 주석</h1> <span>Spring!</span>
- 표준 HTML 주석 (
<!-- xxx -->
)- 자바스크립트의 표준 HTML 주석은 타임리프가 렌더링 하지 않고, 그대로 남겨둔다.
- 타임리프 파서 주석 (
<!--/* xxx */-->
,<!--/*--> xxx <!--*/-->
)- 타임리프 파서 주석은 타임리프의 진짜 주석이다. 렌더링에서 주석 부분을 제거한다.
- 타임리프 프로토타입 주석 (
<!--/*/ xxx /*/-->
)- HTML 파일을 웹 브라우저에서 그대로 열어보면 HTML 주석이기 때문에 이 부분이 웹 브라우저가 렌더링하지 않는다.
- 타임리프 렌더링을 거치면 이 부분이 정상 렌더링 된다.
- 즉, HTML 파일을 그대로 열어보면 주석처리가 되지만, 타임리프를 렌더링 한 경우에만 보이는 기능이다.
- 표준 HTML 주석 (
타임리프 렌더링 시 코드 및 html 화면
-
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>예시</h1> <span>Spring!</span> <h1>1. 표준 HTML 주석</h1> <!-- <span th:text="${data}">html data</span> --> <h1>2. 타임리프 파서 주석</h1> <h1>3. 타임리프 프로토타입 주석</h1> <span>Spring!</span> </body> </html> 결과 <h1>예시</h1> <span>Spring!</span> <h1>1. 표준 HTML 주석</h1> <!-- <span th:text="${data}">html data</span> --> <h1>2. 타임리프 파서 주석</h1> <h1>3. 타임리프 프로토타입 주석</h1> <span>Spring!</span>
- 타임리프 프로토타입을 보면
<span>Spring!</span>
이 렌더링 되었다.
- 타임리프 프로토타입을 보면
12. 타임리프 블록 태그
<th:block>
은 HTML 태그가 아닌 타임리프의 유일한 자체 태그다.
BasicController 추가
-
@GetMapping("/block") public String block(Model model) { addUsers(model); return "basic/block"; }
/block.html
-
/resources/templates/basic/block.html
-
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <th:block th:each="user : ${users}"> <div> 사용자 이름1 <span th:text="${user.username}"></span> 사용자 나이1 <span th:text="${user.age}"></span> </div> <div> 요약 <span th:text="${user.username} + ' / ' + ${user.age}"></span> </div> </th:block> </body> </html>
실행결과
-
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div> 사용자 이름1 <span>UserA</span> 사용자 나이1 <span>10</span> </div> <div> 요약 <span>UserA / 10</span> </div> <div> 사용자 이름1 <span>UserB</span> 사용자 나이1 <span>20</span> </div> <div> 요약 <span>UserB / 20</span> </div> <div> 사용자 이름1 <span>UserC</span> 사용자 나이1 <span>30</span> </div> <div> 요약 <span>UserC / 30</span> </div> </body> </html>
<div>
태그 2개가 연달아 반복되었다. th:each 만으로는 해결할 수 없는 문제이다.<div th:each="user : ${users}">
로 할 수는 있으나<div>...</div>
가 남게 된다.<th:block>
> 은 렌더링시 제거된다.
13. 자바스크립트 인라인
- 타임리프는 자바스크립트에서 타임리프를 편리하게 사용할 수 있는 자바스크립트 인라인 기능을 제공한다. 자바스크립트 인라인 기능은 다음과 같이 적용하면 된다.
<script th:inline="javascript">
BasicController 추가
-
@GetMapping("/javascript") public String javascript(Model model) { model.addAttribute("user", new User("userA", 10)); addUsers(model); return "basic/javascript"; }
javascript.html
-
/resources/templates/basic/javascript.html
-
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <!-- 자바스크립트 인라인 사용 전 --> <script> var username = [[${user.username}]]; var age = [[${user.age}]]; //자바스크립트 내추럴 템플릿 var username2 = /*[[${user.username}]]*/ "test username"; //객체 var user = [[${user}]]; </script> <!-- 자바스크립트 인라인 사용 후 --> <script th:inline="javascript"> var username = [[${user.username}]]; var age = [[${user.age}]]; //자바스크립트 내추럴 템플릿 var username2 = /*[[${user.username}]]*/ "test username"; //객체 var user = [[${user}]]; </script> <!-- 자바스크립트 인라인 each --> <script th:inline="javascript"> [# th:each="user, stat : ${users}"] var user[[${stat.count}]] = [[${user}]]; [/] </script> </body> </html>
결과
자바스크립트 인라인 사용 전 - 결과
-
<!-- 자바스크립트 인라인 사용 전 --> <script> var username = userA; var age = 10; //자바스크립트 내추럴 템플릿 var username2 = /*userA*/ "test username"; //객체 var user = BasicController.User(username=userA, age=10); </script>
자바스크립트 인라인 사용 후 - 결과
-
<!-- 자바스크립트 인라인 사용 후 --> <script> var username = "userA"; var age = 10; //자바스크립트 내추럴 템플릿 var username2 = "userA"; //객체 var user = {"username":"userA","age":10}; </script>
텍스트 렌더링
var username = [[${user.username}]];
- 인라인 사용 전 :
var username = userA;
- 인라인 사용 후 :
var username = "userA";
- 인라인 사용 전 :
- 의도한 바는 “userA” 이지만, 인라인 사용 전에는 userA 라는 변수로 되어있다.
- 인라인 사용 후 렌더링 결과를 보면 문자 타입인 경우 “(큰 따옴표) 를 포함해준다.
- age 는
"
가 필요없기 때문에 정상 렌더링 된다. - 추가로 자바스크립트에서 문제가 될 수 있는 문자가 포함되어 있으면 이스케이프 처리도 해준다. 예)
"
->\"
자바스크립트 내추럴 템플릿
- 타임리프는 HTML 파일을 직접 열어도 동작하는 내추럴 템플릿 기능을 제공한다. 자바스크립트 인라인 기능을 사용하면 주석을 활용해서 이 기능을 사용할 수 있다.
var username2 = /*[[${user.username}]]*/ "test username";
- 사용 전 :
var username2 = /*userA*/ "test username";
- 사용 후 :
var username2 = "userA";
- 사용 전 :
- 인라인 사용 전에는
/*userA*/
가 js 의 주석이므로 그대로 들어간다. - 인라인을 사용하면 기대한 대로 ‘userA’ 가 출력되며, html 문서로 그대로 열면
"test username"
이 나온다.
객체
- 타임리프의 자바스크립트 인라인 기능을 사용하면 객체를 JSON으로 자동으로 변환해준다.
var user = [[${user}]];
- 사용 전 :
var user = BasicController.User(username=userA, age=10);
- 사용 후 :
var user = {"username":"userA","age":10};
- 사용 전 :
- 인라인 사용 전은 객체의 toString()이 호출된 값이다.
- 인라인 사용 후는 객체를 JSON으로 변환해준다.
자바스크립트 인라인 each
-
<!-- 자바스크립트 인라인 each --> <script th:inline="javascript"> [# th:each="user, stat : ${users}"] var user[[${stat.count}]] = [[${user}]]; [/] </script>
- 문법은
[#th:each: ~][/]
이다. 위 코드 참고
자바스크립트 인라인 each 결과
-
<script> var user1 = {"username":"userA","age":10}; var user2 = {"username":"userB","age":20}; var user3 = {"username":"userC","age":30}; </script>
14. 템플릿 조각
- 웹 페이지를 개발할 때는 공통 영역이 많이 있다.
- 예를 들어서 상단 영역이나 하단 영역, 좌측 카테고리 등등 여러 페이지에서 함께 사용하는 영역들이 있다.
- 이런 부분을 코드를 복사해서 사용한다면 변경시 여러 페이지를 다 수정해야 하므로 상당히 비효율적이다.
- 타임리프는 이런 문제를 해결하기 위해 템플릿 조각과 레이아웃 기능을 지원한다.
TemplateController
-
package hello.thymeleaf.basic; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/template") public class TemplateController { @GetMapping("/fragment") public String template(){ return "template/fragment/fragmentMain"; } }
footer.html
-
/resources/templates/template/fragment/footer.html
-
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <body> <footer th:fragment="copy"> 푸터 자리 입니다. </footer> <footer th:fragment="copyParam (param1, param2)"> <p>파라미터 자리 입니다.</p> <p th:text="${param1}"></p> <p th:text="${param2}"></p> </footer> </body> </html>
- th:fragment 가 있는 태그는 다른곳에 포함되는 코드 조각으로 이해하면 된다.
fragmentMain.html
-
/resources/templates/template/fragment/fragmentMain.html
-
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>부분 포함</h1> <h2>부분 포함 insert</h2> <div th:insert="~{template/fragment/footer :: copy}"></div> <h2>부분 포함 replace</h2> <div th:replace="~{template/fragment/footer :: copy}"></div> <h2>부분 포함 단순 표현식</h2> <div th:replace="template/fragment/footer :: copy"></div> <h1>파라미터 사용</h1> <div th:replace="~{template/fragment/footer :: copyParam ('데이터1', '데이터2')}"></div> </body> </html>
template/fragment/footer :: copy
:template/fragment/footer.html
템플릿에 있는``th:fragment=”copy”` 라는 부분을 템플릿 조각으로 가져와서 사용한다는 의미이다.
부분 포함 insert
-
<div th:insert="~{template/fragment/footer :: copy}></div>
-
<h2>부분 포함 insert</h2> <div> <footer> 푸터 자리 입니다. </footer> </div>
<div></div>
를 포함해서 출력
부분 포함 replace
-
<div th:replace="~{template/fragment/footer :: copy}"></div>
-
<h2>부분 포함 replace</h2> <footer> 푸터 자리 입니다. </footer>
<div></div>
가 대체된다.
부분 포함 단순 표현식
-
<div th:replace="template/fragment/footer :: copy"></div>
-
<h2>부분 포함 단순 표현식</h2> <footer> 푸터 자리 입니다. </footer>
~{...}
를 사용하는 것이 원칙이지만 템플릿 조각을 사용하는 코드가 단순하면 이 부분을 생략할 수 있다.
파라미터 사용
-
<div th:replace="~{template/fragment/footer :: copyParam ('데이터1', '데이터2')}"></ div>
-
<
footer th:fragment="copyParam (param1, param2)">
: 이 태그에 param1, param2 값으로 ‘데이터1’, ‘데이터2’ 가 출력된다. -
<footer th:fragment="copyParam (param1, param2)"> <p>파라미터 자리 입니다.</p> <p th:text="${param1}"></p> <p th:text="${param2}"></p> </footer>
15. 템플릿 레이아웃1
- 코드 조각을 레이아웃에 넘겨서 사용하는 방법에 대해서 알아본다.
- 예를 들어서 <head>에 공통으로 사용하는 css , javascript 같은 정보들이 있는데 이러한 공통 정보들을 한 곳에 모아두고, 공통으로 사용하지만, 각 페이지마다 필요한 정보를 더 추가해서 사용하고 싶다면 다음과 같이 사용하면 된다.
TemplateController
-
@GetMapping("/layout") public String layout(){ return "template/layout/layoutMain"; }
base.html
-
<html xmlns:th="http://www.thymeleaf.org"> <head th:fragment="common_header(title,links)"> <title th:replace="${title}">레이아웃 타이틀</title> <!-- 공통 --> <link rel="stylesheet" type="text/css" media="all" th:href="@{/css/awesomeapp.css}"> <link rel="shortcut icon" th:href="@{/images/favicon.ico}"> <script type="text/javascript" th:src="@{/sh/scripts/codebase.js}"></script> <!-- 추가 --> <th:block th:replace="${links}" /> </head>
- 공통으로 사용할 base layout 이다.
<head th:fragment="common_header(title,links)">
를 통해서 title 과 links 를 받는다.- ${title} 부분에 title 태그가 replace 될 것이고,
- ${links} 부분에 link 태그가 replace 될 것이다.
layoutMain.html
-
/resources/templates/template/layout/layoutMain.html
-
common_header(~{::title},~{::link}) 를 통해 title 과 link 를 넘겨준다.
-
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head th:replace="template/layout/base :: common_header(~{::title},~{::link})"> <!-- 넘겨지는 title 과 link(s) --> <title>메인 타이틀</title> <link rel="stylesheet" th:href="@{/css/bootstrap.min.css}"> <link rel="stylesheet" th:href="@{/themes/smoothness/jquery-ui.css}"> </head> <body> 메인 컨텐츠 </body> </html>
결과
-
<!DOCTYPE html> <html> <head> <title>메인 타이틀</title> <!-- 공통 --> <link rel="stylesheet" type="text/css" media="all" href="/css/awesomeapp.css"> <link rel="shortcut icon" href="/images/favicon.ico"> <script type="text/javascript" src="/sh/scripts/codebase.js"></script> <!-- 추가 --> <link rel="stylesheet" href="/css/bootstrap.min.css"><link rel="stylesheet" href="/themes/smoothness/jquery-ui.css"> </head> <body> 메인 컨텐츠 </body> </html>
- 공통 부분은 base.html 이 원래 가지고 있던 것이다.
- 추가 부분은 layoutMain 에서 넘어온 것이다. title 태그 포
16. 템플릿 레이아웃2
- 앞서 이야기한 개념을
,head>
정도에만 적용하는게 아니라<html>
전체에 적용할 수도 있다.
TemplateController
-
@GetMapping("/layoutExtend") public String layoutExtend(){ return "template/layoutExtend/layoutExtendMain"; }
layoutFile.html
-
/resources/templates/template/layoutExtend/layoutFile.html
-
<!DOCTYPE html> <html th:fragment="layout (title, content)" xmlns:th="http://www.thymeleaf.org"> <head> <title th:replace="${title}">레이아웃 타이틀</title> </head> <body> <h1>레이아웃 H1</h1> <div th:replace="${content}"> <p>레이아웃 컨텐츠</p> </div> <footer> 레이아웃 푸터 </footer> </body> </html>
- title 과 content 를 받아서 title 태그와 div 태그를 대체한다.
layoutFile.html
을 보면 기본 레이아웃을 가지고 있는데,<html>
에th:fragment
속성이 정의되어 있다. 이 레이아웃 파일을 기본으로 하고 여기에 필요한 내용을 전달해서 부분부분 변경하는 것으로 이해하면 된다.
layoutExtendMain.html
-
/resources/templates/template/layoutExtend/layoutExtendMain.html
-
<!DOCTYPE html> <html th:replace="~{template/layoutExtend/layoutFile :: layout(~{::title},~{::section})}" xmlns:th="http://www.thymeleaf.org"> <head> <title>메인 페이지 타이틀</title> </head> <body> <section> <p>메인 페이지 컨텐츠</p> <div>메인 페이지 포함 내용</div> </section> </body> </html> 생성
layoutExtendMain.html
는 현재 페이지인데,<html>
자체를th:replace
를 사용해서 변경하는 것을 확인할 수 있다. 결국layoutFile.html
에 필요한 내용을 전달하면서 자체를layoutFile.html
로 변경한다.
결과
-
<!DOCTYPE html> <html> <head> <title>메인 페이지 타이틀</title> </head> <body> <h1>레이아웃 H1</h1> <section> <p>메인 페이지 컨텐츠</p> <div>메인 페이지 포함 내용</div> </section> <footer> 레이아웃 푸터 </footer> </body> </html> 생성
layoutFile.html
을 기반으로 변경되었다.
댓글남기기