티스토리 뷰

728x90

Thymeleaf 학습

  • Thymeleaf의 특징을 알아본다
  • 서버에서 가공한 데이터를 Thymleaf라는 템플릿 엔진을 활용하여 클라이언트에 랜더링 하는 방법을 학습
  • 기본적인 Thymeleaf 문법 학습

3.1 Thymeleaf 소개

File -> Settings -> Build,Execution,Deployment -> Compiler 에서 Build project automatically를 체크

File -> Settings -> Advanced Settings 선택 후 Allow auto-make to start even if developed application is currently running 을 체크

확장 프로그램 Live Reload 설치

    @GetMapping(value = "/ex02")
    public String thymeleafExample02(Model model){
        ItemDTO itemDTO = new ItemDTO();
        itemDTO.setItemDetail("상품 상세 설명");
        itemDTO.setItemNm("테스트 상품1");
        itemDTO.setPrice(10000);
        itemDTO.setRegTime(LocalDateTime.now());

        model.addAttribute("itemDTO", itemDTO);
        model.addAttribute("regTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy.MM.dd a HH:mm:ss")));
        return "thymeleafEx/thymeleafEx02";
    }
  • 시간을 포맷하고 싶으면 이런식으로 넣어도 되지만 혼자 튀게 된다. 초기에 수정하고 싶으면 DTO를 수정

웹 브라우저에서 Thymeleaf 파일 열어보기

templates -> thymeleafEx 경로에 thymeleafEx01.html 작성
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <p th:text="${data}">타임리프 예제?</p>
</body>
</html>
  • th:text="${data}" thymeleaf 문법

Thymeleaf 예제용 컨트롤러 클래스 만들기

com.shopping.project.controller 경로에 ThymeleafExController 클래스 작성
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.ui.Model;


@Controller
@RequestMapping(value="/thymeleaf") //localhost9091/thymeleaf            --------- 1.
public class ThymeleafExController {

    @GetMapping(value = "/ex01")        //localhost9091/thymeleaf/ex01
    public String thymeleafExample01(Model model){
        model.addAttribute("data",  "타임리프 예제 입니다..");  // 모델을 이용한 데이터 전달    -- 2.
        return "/thymeleafEx/thymeleafEx01";         // 뷰                            ---------- 3.
    }
    1. 클라이언트의 요청에 대해서 어떤 컨트롤러가 처리할지 매핑하는 어노테이션. url에 "/thymeleaf경로로 오는 요청을 ThymeleafEController이 처리하도록 한다.
    1. model 객체를 이용해 뷰에 전달한 데이터를 key, value 구조로 넣어준다
    1. templates 폴더를 기준으로 뷰의 위치와 이름(thymeleafEx01.html)을 반환한다 --- 112p
resources.templates.thymeleafEx 경로에 thymeleafEx01.html 작성
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <p th:text="${data}">타임리프 예제?</p>
</body>
</html>

3.2 Spring Boot Devtools

  • 따로 재시작 하지 않고 html 파일 수정 했을 때 업데이트 해주는 기능
  • 크롬 확장프로그램 LiveReload 설치
  • 모든 사이트에서 적용 가능하도록 옵션 선택
  • setting 에서 Build project automatically 및 Allow auto-make to start even if developed .... 체크
pom.xml 의존성 추가
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
    </dependency>

application.properties Live Reload 적용 설정 추가하기
spring.devtools.livereload.enabled=true
application.properties Property Defaults 설정 추가하기
  • 실제 적용 할 때는 운영환경과 개발 환경의 설정을 분리 후 운영환경에서는 캐싱을 사용, 캐발환경에서는 캐싱 기능을 꺼두는 방법으로 사용
  • spring.thymeleaf.cache = false

3.3 Thymeleaf 예제 진행

th:text를 이용한 상품 데이터 출력용 DTO 클래스
  • 경로 : com.shopping.project.dto에 ItemDTO 클래스 생성
package com.shopping.project.dto;


import lombok.Getter;
import lombok.Setter;

import java.time.LocalDateTime;

@Getter
@Setter
public class ItemDTO {

    private Long id;
    private String itemNm;
    private Integer price;
    private String itemDetail;
    private String sellStatCd;
    private LocalDateTime regTime;
    private LocalDateTime updateTime;
}
  • ItemDTO 객체를 하나 생성 후 모델에 데이터를 담아서 뷰에 전달 합니다.
th:text를 이용한 상품 데이터 출력용 컨트롤러 클래스
  • 경로 : com.shopping.project.controller 에 ThymeleafExController 클래스 생성
package com.shopping.project.controller;


import com.shopping.project.dto.ItemDTO;
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 java.time.Clock;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping(value="/thymeleaf") //localhost9091/thymeleaf
public class ThymeleafExController {

    @GetMapping(value = "/ex01")        //localhost9091/thymeleaf/ex01
    public String thymeleafExample01(Model model){
        model.addAttribute("data",  "타임리프 글아라라라니다.");  // 모델을 이용한 데이터 전달
        return "/thymeleafEx/thymeleafEx01";         // 뷰
    }

    @GetMapping(value = "/ex02")
    public String thymeleafExample02(Model model){
        ItemDTO itemDTO = new ItemDTO();
        itemDTO.setItemDetail("상품 상세 설명");
        itemDTO.setItemNm("테스트 상품1");
        itemDTO.setPrice(10000);
        itemDTO.setRegTime(LocalDateTime.now());

        model.addAttribute("itemDTO", itemDTO);
        model.addAttribute("regTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy.MM.dd a HH:mm:ss")));
        return "thymeleafEx/thymeleafEx02";
    }


}
  • 전달받은 itemDTO 객체를 th:text를 이용하여 출력
th:text를 이용한 상품 데이터 출력용 thymeleaf 파일
  • 경로 : resources.templates.thymeleafEx 에 thymeleafEx02.html 생성
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>상품 데이터 출력 예제</h1>
    <div>
        상품명 : <span th:text="${itemDTO.itemNm}"></span>
    </div>
    <div>
        상품 상세 설명 : <span th:text="${itemDTO.itemDetail}"></span>
    </div>
    <div>
        상품 등록일 : <span th:text="${regTime}"></span>
    </div>
    <div>
        상품 가격 : <span th:text="${itemDTO.price}"></span>
    </div>
</body>
</html>

예제2 실행 결과 - 시간 포맷 설정

th:each를 이용한 상품 리스트 출력용 컨트롤러
  • 경로 : com.shopping.project.controller 에 ThymeleafExController에 코드 추가
 @GetMapping(value ="/ex03")
    public String thymeleafExample03(Model model){

        List<ItemDTO> itemDTOList = new ArrayList<>();

        for (int i=1; i<=10; i++){                     --------------- 1.
            ItemDTO itemDTO = new ItemDTO();
            itemDTO.setItemDetail("상품 상세 " + i);
            itemDTO.setItemNm("테스트 상품" + i);
            itemDTO.setPrice(1000*i);
            itemDTO.setRegTime(LocalDateTime.now());

            itemDTOList.add(itemDTO);
        }

        model.addAttribute("itemDTOList", itemDTOList);        ------- 2.
        return "thymeleafEx/thymeleafEx03";
    }
    1. 반복문을 통해 화면에서 출력할 10개의 itemDTO 객체를 만들어서 itemDTOList에 넣는다
    1. 화면에서 출력할 itemDTOList를 model에 담아서 View에 전달
th:each를 이용한 상품 리스트 출력용 thymeleaf파일
  • 경로 : resources.templates.thymeleafEx 에 thymeleafEx03.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">
        <thead>
            <tr>
                <td>순번</td>
                <td>상품명</td>
                <td>상품설명</td>
                <td>가격</td>
                <td>상품등록일</td>
            </tr>
        </thead>
        <tbody>
            <tr th:each="itemDTO, status: ${itemDTOList}">        ------ 1.
                <td th:text="${status.index}"></td>                ------ 2.
                <td th:text="${itemDTO.itemNm}"></td>
                <td th:text="${itemDTO.itemDetail}"></td>
                <td th:text="${itemDTO.price}"></td>
                <td th:text="${itemDTO.regTime}"></td>
            </tr>
        </tbody>
    </table>
</body>
</html>
    1. th:each를 이용하면 자바의 for문 처럼 반복문을 사용할 수 있다. 전달받은 itemDTOList에 있는 데이터를 하나씩 꺼내와서 itemDTO에 담아준다. status에는 현재 반복에 대한 상태 데이터가 존재한다. 변수명은 status 대신 다른것을 사용해도 된다.
    1. 현재 순회하고 있는 데이터의 인덱스를 출력한다.

예제 3 실행 결과

728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/08   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함