JAVA/Spring

[Java / Spring] - Spring - SpringBoot thymeleaf 개념 및 사용법

nam_ji 2024. 9. 27. 18:33

Spring - SpringBoot thymeleaf 개념 및 사용법

thymeleaf란

  • 타임리프는 컨트롤러가 전달하는 데이터를 이용해 동적으로 화면을 만들어주는 역할을 하는 뷰 템플릿 엔진입니다.
  • 타임리프의 특징으로
    1. 서버상에서 동작하지 않아도 HTML 파일의 내용을 바로 확인할 수 있습니다.
    2. 순수 HTML 구조를 유지합니다.
  • s


application-properties

  • 타임리프를 사용하기 전, 몇가지 설정을 합니다.
    • spring.thymeleaf.prefix=classpath:/template/
      spring.thymeleaf.suffix=.html
      spring.thymeleaf.cache=false
      spring.thymeleaf.check-template-location=true
      spring.thymeleaf.mode=HTML
    • 설정에 대한 설명
      더보기
      • spring.thymeleaf.prefix=classpath:/templates/
        • 타임리프 템플릿 파일들이 위치한 기본 경로를 지정합니다.
        • classpath:/template/은 클래스패스 아래에 있는 template 폴더에서 템플릿을 찾겠다는 뜻입니다.
        • 타임리프가 렌더링할 템플릿 파일은 이 경로에서 찾아지게 됩니다.
      • spring.thymeleaf.suffix=.html
        • 타임리프 템플릿 파일들의 기본 확장자를 지정합니다.
        • .html이므로, 타임리프는 템플릿을 찾을 때 자동으로 .html 확장자를 가진 파일을 찾아서 사용하게 됩니다.
        • 예를 들어, 컨트롤러에서 index라는 템플릿을 요청하면 실제로는 classpath:/template/index.html 파일을 찾게 됩니다.
      • spring.thymeleaf.cache=false
        • 타임리프 템플릿을 캐시할지 여부를 설정합니다.
        • false로 설정되어 있으므로 템플릿 파일이 변경될 때마다 즉시 반영되며 캐싱되지 않습니다.
        • 개발 환경에서 템플릿을 수정할 때 변경사항이 즉시 반영되도록 하기 위해 사용됩니다.
        • 운영 환경에서는 성능을 위해 true로 설정하는 것이 일반적입니다.
      • spring.thymeleaf.check-template-location=true
        • 지정된 위치에 타임리프 템플릿 파일이 존재하는지 체크할지 여부를 설정합니다.
        • true로 설정하면 Spring Boot는 애플리케이션 시작 시에 지정된 경로에 템플릿 파일이 있는지 확인합니다.
        • 템플릿이 없으면 애플리케이션이 시작되지 않고 오류를 발생시킵니다.
        • 이를 통해 누락된 템플릿 파일을 빠르게 감지할 수 있습니다.
      • spring.thymeleaf.mode=HTML
        • 타임리프가 어떤 모드로 템플릿을 렌더링할지를 정의합니다.
        • HTML 모드로 설정되어 있으므로 타임리프는 HTML5를 기반으로 템플릿을 처리하며, 이는 주로 웹 애플리케이션에서 사용됩니다.
        • HTML 외에도 XML이나 텍스트 모드 등 다른 모드로 설정할 수 있지만, HTML 모드는 가장 일반적으로 사용됩니다.

코드

1. html & css

  • 간단하게 html과 css를 만들어 thymeleaf를 사용하는 것을 보여드리겠습니다.
  • 보통 templates에 html을 static에 css와 js를 관리합니다.
  • html
    • <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <link rel="stylesheet" href="/style.css">
          <title>thymeleaf 테스트</title>
      </head>
      <body>
      <div class="container">
          <h1 class="font">타임리프 테스트</h1>
      </div>
      </body>
      </html>
  • css
    • .container {
          width: 500px;
          height: 500px;
          background-color: green;
      
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
      
          display: flex;
          align-items: center;
          justify-content: center;
      }
      
      .font {
          font-weight: bold;
      }

2. controller

  • thymeleaf로 controller를 설정할 때에는 @RestController가 아닌 @Controller를 사용하고
  • @GetMapping으로 해당 메서드에 대한 api를 설정합니다.
  • return 타입으로 내가 templates에 설정한 html의 파일 명을 return해주면 해당 html이 호출될 것입니다.
    • package com.namji.thymeleafstudy.controller;
      
      import org.springframework.stereotype.Controller;
      import org.springframework.web.bind.annotation.GetMapping;
      
      @Controller
      public class HomeController {
        @GetMapping("/")
        public String home() {
          return "index";
        }
      }

결과

  • Spring 프로젝트는 따로 지정한 값이 없다면 로컬 주소 값이 localhost:8080입니다.
  • 브라우저에 해당 주소를 입력하면 아래의 화면을 확인할 수 있습니다.