Spring

[SpringBoot] SpringBoot에서 thymeleaf 사용하기

우주유령 2022. 3. 7. 23:29
728x90
반응형

뷰쪽 템플릿을 뭘 쑬까 고민하다가 thymeleaf를 써보기로 했다.

Spring에서 많이 쓰던 jsp는 SpringBoot에서는 잘 안쓴다. 공식 문서에도 나와있다.
https://docs.spring.io/spring-boot/docs/current/reference/html/web.html#web.servlet.spring-mvc.template-engines



Spring initializr에서 dependency에 thymeleaf를 추가해주면 프로젝트 생성할 때부터 추가되어 있다.

 

그냥 build.gradle에 dependency를 추가해도 된다.

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
}

 

기본적으로 template을 사용하는 파일은 resources / templates 안에서 찾도록 되어있다.

애러처럼 templates폴더를 생성하고 thymeleaf를 이용해 html을 만들자.

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

controller도 만들자

@Controller
public class HelloController {
    @GetMapping("hello")
    public String hello(Model model) {
        model.addAttribute("data", "spring");
        return "hello";
    }
}

1. xmlns:th를 선언해줘야 한다.

2. th:test로 텍스트를 대체할 수 있다.

3. controller에서 Model객체(Spring에서제공해줌) 에 {key = data, value=spring} 이런식으로 값을 넣어주면 $표시로 thymeleaf에서 가져올 수 있다.

 

자세한 문법은 공식 사이트 참고하자

https://www.thymeleaf.org/

728x90
반응형