Spring_boot/Project

[Spring] Thymeleaf 사용하기

달의요정루나 2021. 8. 7. 22:07

- 프로젝트 설정

New Spring Starter Project에서 Spring Boot Devtools, Lombok, Thymeleaf, Spring Web Starter로 설정한다.

 

- 새로운 소프트웨어 설치

1) Help에서 Install New Software로 들어간다.

2) Work with에서 Lastest Eclipse Release를 선택한다.

3) Web, XML, Java EE and OSGI Enterprise Development를 선택하고 Next를 누른다음 그뒤로 나오는 약관동의를 하고  설치한다. 

 

- 기타 환경 설정

Window -> Preferences -> General -> Workspace로 가서 UTF-8로 지정한다.

- application.properties 설정

1) Thymeleaf는 기본적으로 '.html' 확장자를 사용하고, 작성된 화면은 서버의 내부에 보관되어 재처리 없이 빠르게 서비스할 수 있는 환경으로 세팅된다.

2) 매번 프로젝트를 재시작하는 불편함이 있기 때문에 개발 시 작성한 화면을 서버 내부에 보관(caching)하지 않도록 설정한다.

보관하지 않도록 설정

- Controller 작성하기

위 사진처럼 패키지를 설정하고 컨트롤러 생성(BoardController.java는 무시해주세요)

package org.zerock.controller;

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

@Controller
public class SampleController {

	@GetMapping("/sample1") //GetMapping을 이용해 더 간단히 get방식의 설정을 지정할 수 있음
	public String sample1(Model model) {
		
		model.addAttribute("greeting", "Hello World");
		//greeting, Hello World는 각각 Key, Value 방식이다.
        
		return "sample1"; //sample1.html 파일과 연결
	}
	
	@GetMapping("/sample2")
	public String sample2(Model model) {
		
		model.addAttribute("intro","안녕하세요!!!");
		
		return "sample2";
	}
}

- 템플릿 페이지 작성

1) template에 마우스를 데고 오른쪽 키를 눌러서 New->Other로 들어간다.

2) Web에서 HTML File로 들어간다.

3) 파일 이름을 지정하고 Finish 버튼을 누른다.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="EUC-KR">
<title>Thymeleaf3</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
	<h1 th:text="${greeting}">Thymeleaf Test Page</h1>
</body>
</html>

4) sample1.html 작성, 컨트롤러에 있는 greeting 키가 body에 있는 greeting과 일치한다. 그래서 출력시 Hello World가 출력된다. 이는 sample2.html과 같다.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="EUC-KR">
<title>Thymeleaf3</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
	<h1 th:text="${intro}">Thymeleaf Test Page</h1>
</body>
</html>

5) sample2.html 작성

 

- 결과

sample1.html
sample2.html