오늘은 Spring에서 Thymeleaf 라이브러리를 사용하는 방법에 대해 알아보고자 한다.
Thymeleaf
타임리프란 템플릿 엔진의 일종으로 html 태그에 속성을 추가하여 페이지를 동적으로 값을 추가하거나 처리 할 수 있도록 만들어주는 Spring 라이브러리를 말한다.
해당 라이브러리를 사용하기 위해서는 Gradle에 아래처럼 라이브러리를 추가해준 다음 빌드 한다.
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
사용 방법
사용예시를 들기 위해 HelloController와 templates폴더 아래 hello.html 파일을 만들어 작동시켜 보았다.
주의 : 스프링부트는 템플릿 의존성 라이브러리를 추가하게 되면 자동적으로 src/main/resources/templates 경로를 기본 경로로 인식하기 때문에, 이를 인지하고 html 파일을 만들어야한다.
- HelloController.java
hello.html 파일에 값을 넘겨주기 위해 Model 파라미터를 받은 다음 addAtttribute 속성을 통해 모델에 값을 넣어 반환한다.
return 값에는 보여주고자 하는 html 파일 이름을 기입한다.
package com.example.inflearn.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HelloController {
@GetMapping("/hello")
public String hello(Model model){
model.addAttribute("data", "hello!!");
return "hello";
}
}
- hello.html
타임리프를 사용할 html 파일에는 <html xmls:th="http://www.thymeleaf.org"> 처럼 태그를 수정해주어야 한다.
컨트롤러에서 넘어온 Model에 접근하기 위해서는 <th: text="${data}"> 처럼 접근이 가능하다.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >
<title>Title</title>
</head>
<body>
<p th:text="'안녕하세요. ' + ${data}"> 안녕하세요. 손님</p>
</body>
</html>
관련 템플릿 문법으로는 공식문서를 참조하도록 하자.
Tutorial: Using Thymeleaf
1 Introducing Thymeleaf 1.1 What is Thymeleaf? Thymeleaf is a modern server-side Java template engine for both web and standalone environments, capable of processing HTML, XML, JavaScript, CSS and even plain text. The main goal of Thymeleaf is to provide a
www.thymeleaf.org
작동 방식
스프링 부트에서 템플릿 엔진은 위와 같이 작동한다.
- 클라이언트에서 요청이 들어온다.
- 내장 톰켓 서버를 거쳐, helloController에서 요청을 처리한다.
- 해당 과정에서 return 값으로 넘어온 html 파일을 찾은 뒤, 템플릿 엔진 처리를 거친 결과 값을 클라이언트에게 반환한다.
하지만 Controller에서 다룰 때, @ResponseBody 라는 에너테이션이 붙어있다면, return 값으로 html 파일을 찾는 것이 아닌, 반환 값으로 객체를 넘긴다면 Json, 그 외에는 String문자열로 반환하니 이를 참고하도록 하자.
'FrameWork > Spring' 카테고리의 다른 글
컨테이너에 빈 등록 및 조회 (0) | 2024.05.27 |
---|---|
IoC, DI 컨테이너 (0) | 2024.05.27 |
JDBC (내용 추가 예정) (0) | 2024.05.20 |
Controller (0) | 2024.05.16 |
MVC Pattern (0) | 2024.05.14 |