본문 바로가기

spring

타임리프 - 기본 기능 (1)

공식 사이트: https://www.thymeleaf.org/

 

Thymeleaf

Integrations galore Eclipse, IntelliJ IDEA, Spring, Play, even the up-and-coming Model-View-Controller API for Java EE 8. Write Thymeleaf in your favourite tools, using your favourite web-development framework. Check out our Ecosystem to see more integrati

www.thymeleaf.org

공식 메뉴얼 - 기본 기능: https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html

 

Tutorial: Using Thymeleaf

1 Introducing Thymeleaf 1.1 What is Thymeleaf? Thymeleaf is a modern server-side Java template engine for both web and standalone environments, capable of processing HTML, XML, JavaScript, CSS and even plain text. The main goal of Thymeleaf is to provide a

www.thymeleaf.org

공식 메뉴얼 - 스프링 통합: https://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html

 

Tutorial: Thymeleaf + Spring

Preface This tutorial explains how Thymeleaf can be integrated with the Spring Framework, especially (but not only) Spring MVC. Note that Thymeleaf has integrations for both versions 3.x and 4.x of the Spring Framework, provided by two separate libraries c

www.thymeleaf.org

 

타임리프 특징

  • 서버 사이드 HTML 렌더링 (SSR)
  • 네츄럴 템플릿
  • 스프링 통합 지원

1. 서버 사이드 HTML 렌더링 (SSR)

타임리프는 백엔드 서버에서 HTML을 동적으로 렌더링 하는 용도로 사용된다.

 

2. 네츄럴 템플릿

타임리프는 순수 HTML을 최대한 유지하는 특징이 있다. 타임리프로 작성한 파일은 HTML을 유지하기 때문에 웹 브라우저에서 파일을 직접 열어도 내용을 확인할 수 있고, 서버를 통해 뷰 템플릿을 거치면 동적으로 변경된 결과를 확인할 수 있다. JSP를 포함한 다른 뷰 템플릿들은 해당 파일을 열면, 예를 들어서 JSP 파일 자체를 그대로 웹 브라우저에서 열어보면 JSP 소스코드와 HTML이 뒤죽박죽 섞여서 웹 브라우저에서 정상적인 HTML 결과를 확인할 수 없다. 오직 서버를 통해서 JSP가 렌더링 되고 HTML 응답 결과를 받아야 화면을 확인할 수 있다. 반면에 타임리프로 작성된 파일은 해당 파일을 그대로 웹 브라우저에서 열어도 정상적인 HTML 결과를 확인할 수 있다. 물론 이 경우 동적으로 결과가 렌더링 되지는 않는다. 하지만 HTML 마크업 결과가 어떻게 되는지 파일만 열어도 바로 확인할 수 있다. 이렇게 순수 HTML을 그대로 유지하면서 뷰 템플릿도 사용할 수 있는 타임리프의 특징을 네츄럴 템플릿 (natural templates)이라 한다.

 

3. 스프링 통합 지원

타임리프는 스프링과 자연스럽게 통합되고, 스프링의 다양한 기능을 편리하게 사용할 수 있게 지원한다. 이 부분은 스프링 통합과 폼 장에서 자세히 알아보겠다.

 

타임리프 사용 선언
<html xmlns:th="http://www.thymeleaf.org">

기본 표현식

더보기

1. 간단한 표현:

◦ 변수 표현식: ${...}

◦ 선택 변수 표현식: *{...}

◦ 메시지 표현식: #{...}

◦ 링크 URL 표현식: @{...}

◦ 조각 표현식: ~{...}

2. 리터럴

◦ 텍스트: 'one text', 'Another one!',…

◦ 숫자: 0, 34, 3.0, 12.3,…

◦ 불린: true, false

◦ 널: null

◦ 리터럴 토큰: one, sometext, main,…

3. 문자 연산: ◦ 문자 합치기: +

◦ 리터럴 대체: |The name is ${name}|

4. 산술 연산:

◦ Binary operators: +, -, *, /, %

◦ Minus sign (unary operator): -

5. 불린 연산:

◦ Binary operators: and, or

◦ Boolean negation (unary operator): !, not

6. 비교와 동등:

◦ 비교: >, <, >=, <= (gt, lt, ge, le)

◦ 동등 연산: ==, != (eq, ne)

7. 조건 연산:

◦ If-then: (if) ? (then)

◦ If-then-else: (if) ? (then) : (else)

◦ Default: (value) ?: (defaultvalue)

8. 특별한 토큰:

◦ No-Operation: _


텍스트 - text, utext

타임리프는 기본적으로 HTML 테그의 속성에 기능을 정의해서 동작한다.

HTML의 콘텐츠(content)에 데이터를 출력할 때는 다음과 같이 th:text 를 사용하면 된다.

HTML 테그의 속성이 아니라 HTML 콘텐츠 영역안에서 직접 데이터를 출력하고 싶으면 다음과 같이 [[...]] 를 사용하면 된다. 컨텐츠 안에서 직접 출력하기 = [[${data}]]

 

@GetMapping("/text-basic")
 public String textBasic(Model model) {
 model.addAttribute("data", "Hello Spring!");
 return "basic/text-basic";
 }
<!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>

간단하게 매핑을 만들고 뷰로 model을 가져와 보여주는 코드이다.

html에 thymeleaf를 보면 2가지 방법으로 model에서 가져온 값을 출력하는 모습이다.

그렇다면 가져온 데이터에 특수기호가 있다면 어떡할까?

Escape

HTML 문서는 < , > 같은 특수 문자를 기반으로 정의된다. 따라서 뷰 템플릿으로 HTML 화면을 생성할 때는 출력하는 데이터에 이러한 특수 문자가 있는 것을 주의해서 사용해야 한다.

model에 값을 "Hello Spring!"이 아니라 "Hello <b>Spring!</b>"이렇게 html 엔티티를 넣어서 보내게 되면 기본적으로 escape처리가 되어 태그글자가 그대로 보여지게 된다. 화면의 소스를 보게 보면 "Hello ;ltB;gtSpring;lt/b;gt" 이런식으로 처리되어 보여지는데 우린 실제 b태그의 기능인 강조를 그대로 사용하고 싶다면 unescaped방식으로 불러오면 된다.

더보기

HTML 엔티티

웹 브라우저는 < 를 HTML 테그의 시작으로 인식한다. 따라서 < 를 테그의 시작이 아니라 문자로 표현할 수 있는 방법이 필요한데, 이것을 HTML 엔티티라 한다. 그리고 이렇게 HTML에서 사용하는 특수 문자를 HTML 엔티티로 변경하는 것을 이스케이프(escape)라 한다. 그리고 타임리프가 제공하는 th:text , [[...]] 는 기본적으로 이스케이스(escape)를 제공한다.

Unescape

타임리프는 다음 두 기능을 제공한다.

th:text  →  th:utext

[[...]]  →  [(...)]

@GetMapping("/text-unescaped")
public String textUnescaped(Model model) {
 model.addAttribute("data", "Hello <b>Spring!</b>");
 return "basic/text-unescaped";
}
<!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>

이번엔 html엔티티를 넣어서 model에 보냇고 html파일에서는 두가지 방식으로 model을 불러왔는데 결과를 보게 되면

이렇듯 다른 결과를 볼 수 있다.

그렇다면 왜 escape효과를 기본으로 만들었을까?

실제 운영되는 사이트들을 예로 들면 게시판에는 많은 사용자들이 말도안되는 내용을 넣을 수 있다.

그렇게되면 이스케이프가 모두 적용이 된다고 생각하면 해당 html파일은 그냥 말도 안되게 깨지게 된다.


변수 - SpringEL

변수 표현식 : ${...}

@GetMapping("/variable")
public String variable(Model model) {
 User userA = new User("userA", 10);
 User userB = new User("userB", 20);
 List<User> 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";
}
@Data
static class User {
 private String username;
 private int age;
 public User(String username, int age) {
 this.username = username;
 this.age = age;
 }
}
<!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>
    <li>${users[1].username} = <span th:text="${users[1].username}"></
        span></li>
    <li>${users[1]['username']} = <span th:text="${users[1]['username']}"></
        span></li>
    <li>${users[1].getUsername()} = <span th:text="${users[1].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>
    <li>${userMap['userB'].username} = <span th:text="${userMap['userB'].username}"></span></li>
    <li>${userMap['userB']['username']} = <span th:text="${userMap['userB']['username']}"></span></li>
    <li>${userMap['userB'].getUsername()} = <span th:text="${userMap['userB'].getUsername()}"></span></li>
</ul>
</body>
</html>

컨트롤러에서는 3가지 방식으로 model에 username을 담았고, 뷰에서도 3가지의 방식으로 모델에 담긴 값을 사용했다.

SpringEL 다양한 표현식 사용

1. Object

  • user.username : user의 username을 프로퍼티 접근 → user.getUsername()
  • user['username'] : 위와 같음 → user.getUsername()
  • user.getUsername() : user의 getUsername() 을 직접 호출

2. List

  • users[0].username : List에서 첫 번째 회원을 찾고 username 프로퍼티 접근 → list.get(0).getUsername()
  • users[0]['username'] : 위와 같음
  • users[0].getUsername() : List에서 첫 번째 회원을 찾고 메서드 직접 호출

3. Map

  • userMap['userA'].username : Map에서 userA를 찾고, username 프로퍼티 접근 → map.get("userA").getUsername()
  • userMap['userA']['username'] : 위와 같음
  • userMap['userA'].getUsername() : Map에서 userA를 찾고 메서드 직접 호출

지역 변수 선언

<h1>지역 변수 - (th:with)</h1>
<div th:with="first=${users[0]}">
 <p>처음 사람의 이름은 <span th:text="${first.username}"></span></p>
</div>

이처럼 모델에 가져온 값을 변수로 저장해서 사용이 가능하다. 단, 선언한 부분 안에서만 사용이 가능하다.

 

'spring' 카테고리의 다른 글

타임리프 - 기본 기능 (3)  (0) 2023.04.10
타임리프 - 기본 기능 (2)  (0) 2023.04.10
PRG Post/Redirect/Get  (0) 2023.04.05
간단한 사이트 만들기  (0) 2023.04.05
요청 매핑 헨들러 어뎁터 구조  (0) 2023.04.04