Search

SpringBoot Thymeleaf 알아보기(기본 개념, 초기 셋팅)

Created time
2022/04/27 12:33
Modified
2022/11/14 12:54
Tags
spring

Template Engine 이란?

: 템플릿 양식에 필요한 데이터를 결합한 html 문서를 만들어 반환해주는 SW
프레젠테이션 계층과 비즈니스 로직을 분리하기 위한 수단
프레젠테이션 계층에서 로직을 쉽게 표현하고, 개발 유연성을 향상, 유지보수 향상시킨다.

Template Engine 종류

JSP(Java Server pages) - SSR
FreeMarker, Groovy, Thymeleaf, Mustache ... - CSR

Server Template Engine (SSR: Server Side Rendering)

서버에서 DB 혹은 API에서 가져온 데이터를 미리 정의된 Templete에 넣고 HTML을 만들어 클라이언트에 전달해주는 역할을 합니다.
HTML에서 고정적인 부분은 템플릿으로 만들어두고, 동적으로 변화하는 부분만 템플릿에 데이터를 끼워 넣는 방식으로 동작합니다.
Rendering 과정
1.
클라이언트는 서버에 페이지 요청
2.
서버는 필요한 데이터를 DB, Application에서 조합해서 HTML 생성, 반환
3.
클라이언트는 반환된 HTML을 실행하여 보여줌

Client Template Engine (CSR: Client Side Rendering)

html 형태로 코드를 작성할 수 있고, 동적으로 DOM을 그릴 수 있습니다.
클라이언트에서 데이터를 받아서 DOM 객체에 동적으로 그려주는 프로세스를 담당합니다.
javascript 라이브러리로 랜더링이 끝난뒤 (즉, HTML DOM이 다 그려진 뒤)에 서버 통신 없이 화면 변경이필요한 경우에 필요합니다.
Rendering 과정
1.
클라이언트에서 공통 템플릿 개발
2.
필요한 데이터 API 요청, 반환
3.
템플릿에 데이터를 교채하고 DOM 객체에 동적으로 그려줌

Template Engine 필요성

1.
대부분 Templete Engine은 HTML에 비해 간단한 문법으로 코드를 줄일 수 있습니다.
2.
데이터만 바뀌는 경우가 많아서, 재사용성을 높일 수 있습니다.
3.
유지보수성 향상시킵니다.

Thymeleaf 셋팅 해보기

의존성 추가

implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
Java
복사

Controller 예시

src/main/java/com/example/developerutils/controller/TestController.java
package com.example.developerutils.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class SampleController { @RequestMapping("/") public String index(Model model) { model.addAttribute("name", "Ryan"); return "hello"; } }
Java
복사

Page 예시

/src/main/resources/templates/hello.html
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"><!--템플릿 엔진을 활용하기 위해 필수--> <head> <meta charset="UTF-8"/> <title>Hello</title> </head> <body> Hello! <h1 th:text="${name}">Name</h1> </body> </html>
HTML
복사

IntelliJ에서 Live reload(실시간 반영) 적용

src/main/resources/application.yml
spring.thymeleaf.cache: false
YAML
복사

테스트 코드 예시

package com.example.developerutils.controller; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; @ExtendWith(SpringExtension.class) @WebMvcTest(SampleController.class) class SampleControllerTest { @Autowired private MockMvc mockMvc; @Test void index() throws Exception { mockMvc.perform(get("/")) .andExpect(status().isOk()) .andExpect(view().name("hello")) .andExpect(model().attribute("name", "Ryan")); } }
Java
복사