Spring/코드로 배우는 스프링부트 웹 프로젝트

코드로 배우는 스프링부트 웹 프로젝트 Day 3

한 면만 쓴 종이 2022. 8. 14. 16:09

/* Annotation들은 스프링부트 프로젝트의 Annotation 정리 페이지에 따로 정리해두었습니다. */

 

[링크 처리]

📎 Thymeleaf의 링크는 '@{ }' 를 이용함

 

SampleController exModel 수정

@GetMapping({"/ex2", "/exInline"})
public void exModel(Model model) {
```
}

 

exLink.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <ul>
        <li th:each="dto : ${list}" >
            <a th:href="@{/sample/exView}">[[${dto}]]</a>
        </li>
    </ul>
</body>
</html>

sample/exLink

@{/sample/exView}를 링크로 하여 생성됨

 

<a th:href="@{/sample/exView(sno=${dto.sno})}">[[${dto}]]</a>

📎 (sno=$dto.sno) => sno 파라미터 추가

 

<a th:href="@{/sample/exView/{sno}(sno=${dto.sno})}">[[${dto}]]</a>

📎 sno를 path에 이용 (ex. /exLink/3)

실행 결과

 

[Thymeleaf의 기본 객체와 LocalDateTime]

Thymeleaf는 내부적으로 기본 객체를 지원함

📎 #numbers, #dates

<li th:each="dto : ${list}" >
    [[${#numbers.formatInteger(dto.sno, 5)}]]
</li>

 

=> sno를 모두 5자리로 출력 가능

 

📎 단점 : LocalDate, LocalDateTime 처리의 복잡함

        ✓ 의존성 추가

implementation group: 'org.thymeleaf.extras', name: 'thymeleaf-extras-java8time'

교재에는 implementation이 아닌 compile으로 작성되어있음. 하지만, compile은 Gradle 4.10 이후로 deprecate되었으므로, implementation으로 대체하여 사용하여야 함. 추가적으로, runtime도 runtimeOnly로 대체되었음

<li th:each="dto : ${list}" >
    [[${dto.sno}]]  --- [[${#temporals.format(dto.regTime, 'yyy/MM/dd')}]]
</li>

=> #temporals 객체를 이용해서 format() 으로 처리

/sample/exLink

 

Thymeleaf의 레이아웃

  • include 방식의 처리
  • 파라미터 방식의 처리

[include 방식의 처리]

  • th:insert
  • th:replace

📎 th:insert

기존 내용의 바깥쪽 택는 우지하면서 추가되는 방식

 

📎 th:replace

기존의 내용을 완전히 대체하는 방식

 

SampleController에 추가

@GetMapping("/exLayout1")
public void exLayout1() {
    
    log.info("exLayout...........");
}

 

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    <div th:fragment="part1">
        <h2>Part 1</h2>
    </div>

    <div th:fragment="part2">
        <h2>Part 2</h2>
    </div>

    <div th:fragment="part3">
        <h2>Part 3</h2>
    </div>

</body>
</html>

part1, 2, 3의 fragment로 나눔

 

exLayout1.html은 방금 만든 fragment1.html의 fragments를 가져와서 사용하는 코드를 작성

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    <h1>Fragment Test</h1>

    <h1>Layout 1 - 1</h1>
    <div th:replace="~{/fragments/fragment1 :: part1}" ></div>

    <h1>Layout 1 - 2</h1>
    <div th:insert="~{/fragments/fragment1 :: part2}" ></div>

    <h1>Layout 1 - 3</h1>
    <th:block th:replace="~{/fragments/fragment1 :: part3}" ></th:block>

</body>
</html>

<div>, <th:block> 와 Thymeleaf의 replace, insert를 이용

 

"~{/fragments/fragment1 :: part2}"

:: 뒤에는 fragment의 이름이나 CSS의 '#id' 같은 선택자 사용 가능

::  사용을 생략하면 해당 파일의 전체를 가져올 수 있음

/sample/exLayout1

fragments/fragment2

<div>
    <hr/>
    <h2>Fragment2 File</h2>
    <h2>Fragment2 File</h2>
    <h2>Fragment2 File</h2>
</div>

 

exLayout1.html에 fragment2.html 전체를 사용하는 코드 추가

<h1>Fragment Test</h1>
<div style="border: 1px solid blue">

<th:block th:replace="~{/fragments/fragment2}" ></th:block>

</div>

:: 를 생략했으므로 fragment2의 전체가 사용됨

/sample/exLayout1

 

 

[파라미터 방식의 처리]

Thymeleaf를 이용하여 특정한 태그를 파라미터처럼 전달해서 다른 th:fragment에서 사용 가능

 

SampleController의 exLayout1()재사용 => @GetMapping 수정

@GetMapping({"/exLayout1", "/exLayout2"})
public void exLayout1() {

    log.info("exLayout...........");
}

fragments/fragment3.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    <div th:fragment="target(first, second)" >
        
        <style>
            .c1 {
                background-color: red;
            }
            .c2 {
                background-color: blue;
                }
        </style>
        
        <div class="c1">
            <th:block th:replace = "${first}"></th:block>
        </div>

        <div class="c2">
            <th:block th:replace = "${second}"></th:block>
        </div>
        
    </div>

</body>
</html>

📎 <div th:fragment="target(first, second)">

target의 파라미터를 first와 second로 받음

 

실제 target을 사용하는 작업은 exLayout2.html로 진행

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">

<th:block th:replace="~{/fragments/fragment3:: target(~{this:: #ulFirst}, ~{this::#ulSecond} )}">

    <ul id="ulFirst">
        <li>AAA</li>
        <li>BBB</li>
        <li>CCC</li>
    </ul>

    <ul id="ulSecond">
        <li>111</li>
        <li>222</li>
        <li>333</li>
    </ul>
    
</th:block>

target을 사용하여 파라미터 2개를 사용

fragment3.html의 코드에 exLayout2.html에서 전달된 태그들이 포함되어서 출력됨

/sample/exLayout2