Java 관련/SpringBoot

[SpringBoot] Thymeleaf01

씨네 2022. 4. 15. 13:08
728x90

타임리프는 템플릿 이라고 할수있습니다.

보통 스프링부트를 뷰나 리엑트를 연결해서 쓰는경우가 많은데 Thymeleaf를 사용해보려고 합니다.

타임리프는 OGNL(Object-Fraph Navigation Language)라고 합니다.

- 자바의 값에 접근하기 위한 오픈소스 표현식 언어

- JSP, Thymeleaf, Groovy 등

- 처음에 SpringBoot에서는 Thymeleaf를 주로 사용한다.(요즘에는 타임리프 사용 잘 안함)

utiliy object

#execInfo

#messages

#uris

#conversions

#dates

#calendars

#numbers

#strings

#objects

#bools

#arrays

#lists

#sets

#maps

#aggregates

#ids

expressions

${...} : message 표현

*{...} : object의 field값 표현

#{...} : *.properties 값 표현

@{...} : link(url) 값 표현

~{...} : 표현식 조각 (참조 가능)

<tag th:text></tag>

<tag th:object></tag>

<tag th:href></tag>

<tag th:each></tag>

<tag th:if></tag>

<tag th:switch><tag th:case></tag></tag>

<tag th:attr></tag>

타임리프는 이렇게 사용하는것!

타임리프에 대한 설명이 있는 페이지입니다. ( 다 영어입니다.. )

그러면 프로젝트를 만들어서 간단한 코드를 보겠습니다!

Spring Starter Project를 만들어주세요!

패키지는 com.boot.leaf로 하겠습니다

 

Spring Boot DevTools / Thymeleaf / Spring Web을 체크하고 만들어줍니다!

pom.xml

<!-- tomcat -->
<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
</dependency>

pom.xml에 사용할 디펜던시를 추가해줍니다.

application.properties

# port
server.port=8787

# encoding
server.servlet.encoding.charset=UTF-8
server.servlet.encoding.force=true
server.servlet.encoding.enabled=true

application.properties에서 포트연결과 인코딩을 잡아줍니다.

 

static에 index를 만들고 실행시켜볼까요??

타임리프에 대한 템플릿입니다!

<html xmlns:th="http://www.thymeleaf.org">

타임리프를 사용하기 위해서는 html 태그안에 해당 내용을 작성해야합니다.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

	<h1>INDEX</h1>

	<a href="hello">hello</a>
	
</body>
</html>

index.html에서 다른파일로 이동하기위해 a태그를 걸어주겠습니다.

com.boot.leaf.controller 패키지를 만들고 그안에 LeafController클래스를 만들어주세요!

LeafController.java

package com.boot.leaf.controller;

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

@Controller
public class LeafController {
	
	@GetMapping("/hello")
	public String hello(Model model) {
		
		model.addAttribute("name", "Thymeleaf");
		
		return "hello";
	}

}

컨트롤러에서 /hello라는 주소를 응답받으면 모델객체에 "name"="Thymeleaf"를 담아서 hello.html로 보냅니다!

templates안에 hello.html을 만들어주세요!

hello.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

	<h1 th:text="${name}">이름이 들어갈 곳 입니다.</h1>
	<a href="/">index</a>
	
</body>
</html>

해당 코드를 작성한뒤 실행하면

Controller에서 value값으로 보내준 Thymeleaf가 출력됩니다.

즉 태그안에 있는것들은 가이드라고 보시면되고 결국에는 타임리프가 덮어씌워서 출력되지않습니다.

아까 템플릿이 있는 홈페이지에 보면 해당 내용이있습니다.

태그 사이에 있는 내용을 th:text="" 안에있는 내용으로 replcae 하게 됩니다.

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

	<h1>INDEX</h1>

	<a href="hello">hello</a><br/>
	<a href="util">utility</a>
	
	
</body>
</html>

a태그 하나 추가해서 util로 보내줍니다!

leafController.java

	@GetMapping("/util")
	public String utility() {
		return "utility";
	}

컨트롤러에는 util메소드를 추가해줍니다.

utility.html 파일도 만들어주세요!

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

	<p th:text="${#calendars.format(#calendars.createNow(), 'yyyy-MM-dd HH:dd')}">#data objects</p>
	<p th:text="${#numbers.formatInteger(3456.1234, 6)}">#numbers objects</p>
	<p th:text="${#strings.toUpperCase('hello, springboot')}">#strings objects</p>
	
	<a href="">index</a>
</body>
</html>

홈페이지에 나와있는 예시 중 몇개만 사용해 보았습니다.

728x90