[스프링 MVC 1편] 타임리프 (Thymeleaf)

강신현·2022년 9월 22일
0

💡 타임리프 (Thymeleaf)

순수 HTML 파일을 웹 브라우저에서 열어도 내용을 확인할 수 있고,
서버를 통해 뷰 템플릿을 거치면 동적으로 변경된 결과를 확인할 수 있다.

  • JSP를 생각해보면, JSP 파일은 웹 브라우저에서 그냥 열면 JSP 소스코드와 HTML이 뒤죽박죽 되어서 정상적인 확인이 불가능하다.
    오직 서버를 통해서 JSP를 열어야 한다.
  • 이렇게 순수 HTML을 그대로 유지하면서 뷰 템플릿도 사용할 수 있는 타임리프의 특징을 네츄럴 템플릿 (natural templates)이라 한다.
  • 스프링 MVC와의 통합 모듈을 제공하며, 애플리케이션에서 JSP로 만든 기능들을 완전히 대체할 수 있다.
  • 순수 HTML 파일을 웹 브라우저에서 열어도 내용을 확인하는 방법
    파일 우클릭 -> "Copy Path/Reference.." -> 인터넷 창에 복사된 url 입력하여 HTML 파일 확인
    👉 HTML을 수정한 뒤 서버를 재시작하지 않고 HTML 파일만 열어 확인 가능

📕 정적 html 👉 뷰 템플릿

타임리프를 사용하여 정적 리소스를 동적인 뷰 템플릿으로 전환해보자.

- 정적 html

  • 경로 : resources>static
<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <link href="../css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container" style="max-width: 600px">
    <div class="py-5 text-center">
        <h2>상품 목록</h2> </div>
    <div class="row">
        <div class="col">
            <button class="btn btn-primary float-end" onclick="location.href='addForm.html'" type="button">상품
                등록</button> </div>
    </div>
    <hr class="my-4">
    <div>
        <table class="table">
            <thead>
            <tr>
                <th>ID</th> <th>상품명</th> <th>가격</th> <th>수량</th>
            </tr>
            </thead>
            <tbody>
            <tr>
                <td><a href="item.html">1</a></td>
                <td><a href="item.html">테스트 상품1</a></td>
                <td>10000</td>
                <td>10</td>
            </tr>
            <tr>
                <td><a href="item.html">2</a></td>
                <td><a href="item.html">테스트 상품2</a></td> <td>20000</td>
                <td>20</td>
            </tr>
            </tbody>
        </table>
    </div>
</div> <!-- /container -->
</body>
</html>

- 뷰 템플릿

  • Controller
@Controller
@RequestMapping("/basic/items")
@RequiredArgsConstructor
public class basicItemController {

    private final ItemRepository itemRepository;

    @GetMapping
    public String items(Model model){
        List<Item> items = itemRepository.findAll();
        model.addAttribute("items", items);
        return "basic/items";
    }

    /**
     * 테스트용 데이터 추가
     */
    @PostConstruct
    public void init(){
        itemRepository.save(new Item("itemA", 10000, 10));
        itemRepository.save(new Item("itemB", 20000, 20));
    }
}
  • 경로 : resources>templates
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <link href="../css/bootstrap.min.css" th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
</head>
<body>
<div class="container" style="max-width: 600px">
    <div class="py-5 text-center">
        <h2>상품 목록</h2> </div>
    <div class="row">
        <div class="col">
            <button class="btn btn-primary float-end"
                    onclick="location.href='addForm.html'"
                    th:onclick="|location.href='@{/basic/items/add}'|"
                    type="button">상품 등록</button> </div>
    </div>
    <hr class="my-4">
    <div>
        <table class="table">
            <thead>
            <tr>
                <th>ID</th> <th>상품명</th> <th>가격</th> <th>수량</th>
            </tr>
            </thead>
            <tbody>
            <tr th:each="item : ${items}">
                <td><a href="item.html" th:href="@{/basic/items/{itemId} (itemId=${item.id})}" th:text="${item.id}">회원 id</a></td>
                <td><a href="item.html" th:href="@{|/basic/items/${item.id}|}" th:text="${item.itemName}">상품명</a></td>
                <td th:text="${item.price}">10000</td>
                <td th:text="${item.quantity}">10</td>
            </tr>
            </tbody>
        </table>
    </div>
</div> <!-- /container -->
</body>
</html>

📕 타임리프 문법

1. 타임리프 사용 선언

<html xmlns:th="http://www.thymeleaf.org">

2. th:href

`속성 변경 💡 타임리프 핵심

  • th:xxx 가 붙은 부분은 서버사이드에서 렌더링 되고, 기존 것을 대체한다.
  • th:xxx 이 없으면 기존 html의 xxx 속성이 그대로 사용된다.
  • HTML을 파일로 직접 열었을 때, th:xxx 가 있어도 웹 브라우저는 th: 속성을 알지 못하므로 무시한다.
  • 따라서 HTML을 파일 보기를 유지하면서 템플릿 기능도 할 수 있다.
  • href="value1" 을 th:href="value2" 의 값으로 변경한다.
  • 타임리프 뷰 템플릿을 거치게 되면 원래 값을 th:xxx 값으로 변경한다. 만약 값이 없다면 새로 생성한다.
  • HTML을 그대로 볼 때는 href 속성이 사용되고, 뷰 템플릿을 거치면 th:href 의 값이 href 로 대체되면서 동적으로 변경할 수 있다.
  • 대부분의 HTML 속성을 th:xxx 로 변경할 수 있다.

3. @{...}

URL 링크 표현식

th:href="@{/css/bootstrap.min.css}"
  • URL 링크 표현식을 사용하면 서블릿 컨텍스트를 자동으로 포함한다.

- 쿼리 파라미터

th:href="@{/basic/items/{itemId}(itemId=${item.id})}" 상품 ID를 선택하는 링크
  • URL 링크 표현식을 사용하면 경로를 템플릿처럼 편리하게 사용할 수 있다.
  • 경로 변수( {itemId} ) 뿐만 아니라 쿼리 파라미터도 생성한다.
    생성 링크: http://localhost:8080/basic/items/1?query=test
th:href="@{/basic/items/{itemId}(itemId=${item.id}, query='test')}"
  • 리터럴 대체 문법(4번 참고)을 활용해서 간단히 사용할 수도 있다.
th:href="@{|/basic/items/${item.id}|}" 상품 이름을 선택하는 링크

4. th:onclick

상품 등록 폼으로 이동 속성 변경

onclick="location.href='addForm.html'"
👉 th:onclick="|location.href='@{/basic/items/add}'|"
  • 리터럴 대체 문법이 사용됨

- |...|

리터럴 대체 문법
문자와 표현식을 분리 하지않고 편리하게 사용할 수 있다.

  • 타임리프에서 문자와 표현식 등은 분리되어 있기 때문에 더해서 사용해야 한다.
<span th:text="'Welcome to our application, ' + ${user.name} + '!'">
  • 다음과 같이 리터럴 대체 문법을 사용하면, 더하기 없이 편리하게 사용할 수 있다.
<span th:text="|Welcome to our application, ${user.name}!|">

5. th:each

모델에 포함된 컬렉션 데이터 변수를 반복하여 사용할 수 있다.

<tr th:each="item : ${items}">
  • 모델에 포함된 items 컬렉션 데이터가 item 변수에 하나씩 포함되고, 반복문 안에서 item 변수를 사용할 수 있다.
  • 컬렉션의 수 만큼 < tr >..< /tr > 이 하위 테그를 포함해서 생성된다.

6. ${...}

변수 표현식
모델에 포함된 값이나, 타임리프 변수로 선언한 값을 조회할 수 있다.

<td th:text="${item.price}">10000</td>
  • 프로퍼티 접근법을 사용한다. ( item.getPrice() )

7. th:text

내용의 값을 th:text 의 값으로 변경한다.

<td th:text="${item.price}">10000</td>
  • 여기서는 10000을 ${item.price} 의 값으로 변경한다.

8. th:value

모델에 있는 item 정보를 획득하고 프로퍼티 접근법으로 출력한다. ( item.getId() )

  • value 속성을 th:value 속성으로 변경한다.
<body>
    <div class="container">
        <div class="py-5 text-center">
            <h2>상품 상세</h2>
        </div>
        <div>
            <label for="itemId">상품 ID</label>
            <input type="text" id="itemId" name="itemId" class="form-control" value="1" th:value="${item.id}" readonly>
        </div>
        ...

9. th:action

HTML form에서 action 에 값이 없으면 현재 URL에 데이터를 전송한다.

  • 상품 등록 폼의 URL과 실제 상품 등록을 처리하는 URL을 똑같이 맞추고 HTTP 메서드로 두 기능을 구분한다.
  • 상품 등록 폼: GET /basic/items/add
  • 상품 등록 처리: POST /basic/items/add
    이렇게 하면 하나의 URL로 등록 폼과, 등록 처리를 깔끔하게 처리할 수 있다.
...
<h4 class="mb-3">상품 입력</h4>
    <form action="item.html"
          th:action
          method="post">
     ...
     </form>
...

강의 출처

[인프런 - 김영한] 스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술

profile
땅콩의 모험 (server)

0개의 댓글