Java

[Spring Boot] 템플릿 엔진 Thymeleaf 사용 방법

cob 2023. 6. 23. 00:57

 

템플릿 엔진이란?
주로 View를 만드는데 사용되지만, 코드 제너레이션 또는 시스템에서 만들어 놓은 이메일 템플릿에 파라미터만 넣어 변경하는 등 여러 가지 상황에 맞게 사용할 수 있다.

 

* 전체 소스 코드
https://github.com/kangilbin/Spring-Boot/tree/master/Tyhmeleaf

 

 


1. Spring Boot에서 자동 구성을 지원하는 템플릿 엔진

Sring Boot는 JSP를 대체할 수 있는 다양한 뷰 템플릿 엔진 지원한다. 이러한 엔진들은 Spring Boot의 자동 구성 기능과 완벽하게 통합되어 개발자 편의성과 애플리케이션의 유지보수성을 높일 수 있다.
* 뷰 템플릿 엔진 종류
1. Thymeleaf
2. FreeMarker
3. Groovy
4. Mustache

 

 

 


2. Spring Boot에서 JSP를 권장하는 않는 이유

Spring Boot에서는 JSP를 자동 구성하는 기능을 제공하지 않는다. Spring Boot는 JSP를 지원하지 않는 이유는 JSP의 동작에는 추가적인 설정이 필요하며, 이는 Spring Boot의 간결하고 자동화된 구성 철학과는 어울리지 않기 때문이다.
  • 복잡한 설정: JSP를 사용하려면 추가적인 설정이 필요하고, 서버의 서블릿 컨테이너에 따라 다양한 설정이 다르게 적용되어야 한다. 이는 Spring Boot의 간결하고 자동화된 구성 철학과는 어울리지 않는다.
  • 제한된 포터블리티: JSP는 특정 서블릿 컨테이너에 종속적인 특성이 있어, JSP 애플리케이션을 다른 서블릿 컨테이너로 이전하기가 어려울 수 있다. Spring Boot는 가능한 한 독립적이고 이식성이 좋은 애플리케이션을 지향하기 때문에, 이러한 종속성을 피하기 위해 JSP를 권장하지 않는다.
  • 성능 및 확장성: JSP는 동적으로 컴파일되고 실행되어야 하기 때문에, 일반적으로 다른 뷰 템플릿 엔진에 비해 성능이 떨어질 수 있다. 또한, JSP는 스레드 안전성에 관련된 문제가 있을 수 있어 확장성 면에서도 제약이 있다.

 

* Spring Boot에서 JSP를 사용하는 방법
Spring Boot 애플리케이션을 WAR 파일로 패키징하고, 해당 WAR 파일을 외부 서블릿 컨테이너(예: Tomcat, Jetty, WildFly 등)에 배포하여 실행해야 한다. 외부 서블릿 컨테이너는 JSP를 처리하고 실행하는 데 필요한 설정과 기능을 제공한다.

 

 


3. Thymeleaf 사용 방법

*공식 문서
https://www.thymeleaf.org/

 

3-1) 의존성 추가

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

 

3-2) View 생성

동적으로 생성되는 View는 src/main/resources/templetes 경로에서 찾게된다.

Context Root Path

 

3-3) Controller 맵핑

package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class SampleController {

    @GetMapping("/hello")
    public String hello(Model model) { // 1) model은 화면에 전달할 데이터들을 담을 수 있다.

        // 2) View의 이름은 return 값의로 표현한다.
        model.addAttribute("name", "coco");
        return "hello";
    }
}
  • Model : View에 전달할 데이터를 Key = value로 담아서 전달할 수 있다.
  • return 타입이 String일 경우 return 되는 값이 View 이름이다.

 

3-4) View model 값 전달하기

* Thymeleaf 기본 문법
https://www.thymeleaf.org/doc/articles/standarddialect5minutes.html
<!DOCTYPE html>
<!--thymeleaf의 th라는 namespace를 추가한다.-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--name 값이 없으면 기본적으로 태그 안에 있는 값이 출력되고, 있다면 해당 값이 출력된다. -->
    <h1 th:text="${name}">Name</h1>
</body>
</html>

출력 결과

 

 

 


4. Test 코드 작성

* 테스트 코드 작성 방법

2023.06.16 - [Java] - [Spring Boot] 단위 테스트(JUnit) 사용 방법

package com.example.demo;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;

import static org.hamcrest.Matchers.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@RunWith(SpringRunner.class)
@WebMvcTest(SampleController.class)
public class SampleControllerTest {

    @Autowired
    MockMvc mockMvc;

    @Test
    public void hello() throws Exception {
        /*
            요청 - "/hello"
            응답
              - 뷰 이름 : hello
              - 모델 name : coco
         */
        mockMvc.perform(get("/hello"))
                .andExpect(status().isOk())      // status가 200인지 확인
                .andDo(print())                  // 렌더링 결과 콘솔에서 확인
                .andExpect(view().name("hello")) // View name이 hello인지 확인
                .andExpect(model().attribute("name", is("coco"))); // model의 name 값이 coco인지 확인
    }

}

테스트 결과 출력

JSP의 경우 서블릿 엔진이 렌더링 하기 때문에 테스트 시에 렌더링 된 결과를 확인하기 어렵다. 하지만 Thymeleaf는 서블릿 컨테이너의 도움 없이 독립적으로 동작하는 엔진이기 때문에 뷰에 렌더링된 결괏값도 쉽게 확인할 수 있다.

 

 

반응형