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

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

한 면만 쓴 종이 2022. 8. 12. 16:58

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

 

[Thymeleaf의 기본 사용법]

dto 패키지 생성 -> SampleDto 클래스 생성

 

DTO란? Data Transfer Object계층 간 데이터 교환을 위해 사용하는 객체로직을 가지지 않는 순수한 데이터 객체(getter & setter 만 가지는 클래스)

 

DAO란?Data Access Object데이터베이스의 data에 접근하기 위한 객체DataBase에 접근하기 위한 로직과 비지니스 로직을 분리하기 위해 사용

@Data
@Builder(toBuilder = true)
public class SampleDTO {

    private Long sno;
    private String first;
    private String last;
    private LocalDateTime regTime;
}

 

SampleController에 추가

@GetMapping({"/ex2"})
public void exModel(Model model) {
    List<SampleDTO> list = IntStream.rangeClosed(1, 20).asLongStream().mapToObj(i -> {
        SampleDTO dto = SampleDTO.builder()
                .sno(i)
                .first("First.." + i)
                .last("Last.." + i)
                .regTime(LocalDateTime.now())
                .build();
        return dto;
    }).collect(Collectors.toList());

    model.addAttribute("list", list);
}

model.addAttribute(String name, Object value) : value객체를 name이름으로 추가함

작성된 SampleDTO의 객체를 Model에 추가해서 전달

 

 

<Thymeleaf의 반복문>

th:each = "변수: ${목록} "

 

ex2.html

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

    <ul>
        <li th:each="dto: ${list}">
            [[${dto}]]
        </li>
    </ul>

</body>
</html>

<li> 태그 내에 dto변수를 만듦. Model로 전달된 데이터는 ${list}로 처리

[[ ]] : 인라인 표현식

SampleController에서 만든 list를 사용

 

실행 결과

[반복문의 상태(state) 객체]

<li th:each="dto, state : ${list}">
    [[${state.index}]] --- [[${dto}]]
</li>

반복문 <li>에는 상태 객체를 만들 수 있음

순번, 인덱스, 홀/짝수 지정 가능

state.index : 0부터 시작

state.count: 1부터 시작

 

실행 결과

 

[제어문 처리]

 

<li th:each="dto, state : ${list}" th:if="${dto.sno % 5 == 0}">
    [[${dto}]]
</li>

[Thymeleaf의 제어문 처리 기능]

5의 배수만 출력

 

실행 결과

<li th:each="dto, state : ${list}" >
    <span th:if="${dto.sno % 5 == 0}" th:text="${'----------------------' + dto.sno}"></span>
    <span th:unless="${dto.sno % 5 == 0}" th:text="${dto.first}"></span>
</li>

Thymeleaf의 th:if , th:unless

sno가 5의 배수일 경우 => sno만 출력

sno가 5의 배수가 아닐 경우 => first 출력

삼항연산자 방식

<li th:each="dto, state : ${list}" th:text="${dto.sno % 5 == 0 }? ${dto.sno}: ${dto.first}">
</li>

+CSS활용

<style>
    .target {
        background-color: red;
    }
</style>

<ul>
    <li th:each="dto, state : ${list}" th:class="${dto.sno % 5 == 0 }?'target'" th:text="${dto}">
    </li>
</ul>

sno가 5의 배수인 경우에만 CSS클래스가 적용되도록 작업

실행 결과

 

[inline속성]

가장 유용한 Thymeleaf 속성

 

SampleController에 추가

@GetMapping({"/exInline"})
public String exInline(RedirectAttributes redirectAttributes) {
    
    log.info("exInline...............");
    
    SampleDTO dto = SampleDTO.builder()
            .sno(100L)
            .first("First..100")
            .last("Last..100")
            .regTime(LocalDateTime.now())
            .build();
    redirectAttributes.addFlashAttribute("result", "success");
    redirectAttributes.addFlashAttribute("dto", dto);
    
    return "redirect:/sample/ex3";
}

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

RedirectAttributes

Get방식

redirect 방식으로 데이터 전달 가능한 방법

URL노출이 되지 않음

.addFlashAttribute()

리다이렉트 직전 플래시에 저장하는 메소드

리다이렉트 후에는 소멸함

 

RedirectAttributes를 이용하여 "/ex3"으로 데이터 전달

 

ex3.html 생성

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

    <h1 th:text="${result}"></h1>
    <h1 th:text="${dto}"></h1>

    <script th:inline="javascript">

        var msg = [[${result}]];
        var dto = [[${dto}]];
    </script>
</body>
</html>

th:inline 의 속성값으로 javascript를 지정

브라우저에서 경로는 "/sample/exInline" 호출 => 리다이렉트 => "/sample/ex3" 호출

 

[th:block]

HTML의 태그가 아닌 오직 Thymeleaf만이 제공하는 자체 태그 => HTML로 처리X

th:text나 th:value등을 써야하는 다른 태그들과 달리 별도의 태그가 필요 없음

 

반복문 문제 해결을 위해 만든 것이 주된 이유

두 개의 반복문을 같이 돌릴 때, 하나의 반복문이 다 돌고 그 후에 나머지 반복문이 도는 것이 아닌 하나씩 돌도록 해줌

하나의 블록으로 처리하는 방식

 

ex2.html 수정

<ul>
    <th:block th:each="dto: ${list}">
        <li th:text="${dto.sno % 5 == 0}?${dto.sno}:$dto.first}"></li>
    </th:block>
</ul>