Spring Boot에서 템플릿 엔진(Thymeleaf)을 활용하여 동적인 콘텐츠를 생성하는 방법을 설명해 드릴게요.
1. 프로젝트 설정
1) Thymeleaf 의존성 추가
Spring Boot 프로젝트를 생성할 때 Thymeleaf를 포함해야 합니다.
pom.xml 또는 build.gradle에 아래 의존성이 포함되어 있어야 합니다.
Maven (pom.xml)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Gradle (build.gradle)
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
}
2. 컨트롤러 생성
src/main/java/com/example/demo/controller/ContentController.java 파일을 생성하고 다음과 같이 작성합니다.
package com.example.demo.controller;
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.util.List;
@Controller
@RequestMapping("/content")
public class ContentController {
@GetMapping("/list")
public String contentList(Model model) {
List<String> articles = List.of("Spring Boot Guide", "Thymeleaf Template", "MVC 구조 이해");
model.addAttribute("articles", articles);
return "content-list"; // content-list.html 템플릿을 반환
}
}
3. Thymeleaf 템플릿 작성
src/main/resources/templates/content-list.html 파일을 만들고 다음과 같이 작성합니다.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>콘텐츠 리스트</title>
</head>
<body>
<h1>콘텐츠 리스트</h1>
<ul>
<li th:each="article : ${articles}" th:text="${article}">콘텐츠 제목</li>
</ul>
</body>
</html>
4. 애플리케이션 실행 및 확인
1) Spring Boot 실행
프로젝트를 실행한 후, 브라우저에서 아래 주소로 접속합니다.
http://localhost:8080/content/list
2) 동적 콘텐츠 확인
브라우저에서 다음과 같은 리스트가 보입니다.
콘텐츠 리스트
- Spring Boot Guide
- Thymeleaf Template
- MVC 구조 이해
5. 추가 기능
1) 상세 페이지 연결
각 콘텐츠를 클릭하면 상세 페이지로 이동하도록 수정합니다.
컨트롤러 업데이트
@GetMapping("/detail")
public String contentDetail(Model model, @RequestParam String title) {
model.addAttribute("title", title);
return "content-detail";
}
템플릿 업데이트
<ul>
<li th:each="article : ${articles}">
<a th:href="@{/content/detail(title=${article})}" th:text="${article}"></a>
</li>
</ul>
이제 Spring Boot + Thymeleaf를 활용하여 동적인 웹 콘텐츠를 생성할 수 있습니다!
'웹' 카테고리의 다른 글
웹사이트 (0) | 2025.02.17 |
---|---|
웹사이트만들기 1일차 (1) | 2025.02.17 |
웹 컨트롤러 (0) | 2025.02.12 |
css, 자바스크립트 추가정 (0) | 2025.02.07 |
HTML,CSS,JavaScript 정리 (1) | 2025.02.07 |