스프링

thymeleaf 템플릿 엔진 동작(기본)

hmjhaha 2024. 1. 10. 12:42

/hello-spring/src/main/resources/templates/hello.html

 

<!DOCTYPE HTML>
<html xmlns:th="https://www.thymeleaf.org"> 
<head>
<title>Hello</title>
<meta http-equi="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<p th:text="'안녕하세요. '+${data}">안녕하세요. 손님</p>
</body>
</html>

 

/hello-spring/src/main/java/hello/hellospring/controller

 

package hello.hellospring.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";
    }
}

 

- 스프링 부트는 톰켓 서버를 내장하고 있다.

 

- url : http://localhost:8080/hello

 @GetMapping("hello") - url 매칭됨

코드 실행 (spring이 모델을 만들어서 넣어줌) - model(data:hello!!)

return의 이름이 hello -> resources/templates 밑에 있는 hello를 찾음 -> hello.html로 이동 (Thymeleaf 템플릿 엔진 처리)


- 컨트롤러에서 리턴 값으로 문자를 반환하면 뷰 리졸버('viewResolver')가 화면을 찾아서 처리한다.

스프링 부트 템플릿엔진 기본 viewName 매핑

'resources:templates/' + {ViewName} + '.html'