ICT Intern/Spring Security

[Spring] Thymeleaf 알아보기

칸타탓 2019. 4. 9. 15:22

Thymeleaf 사용하는 이유는?

 

  • 텍스트, HTML, XML, Javascript, CSS를 생성할 수 있는 템플릿 엔진
  • 순수 HTML로 템플릿 작성 가능
  • Spring Boot에서 사용 권장 (Spring Boot에서는 JSP를 추천하지 않는다.)

 

* Gradle 추가한 후 사용한다.

compile 'org.springframework.boot:spring-boot-starter-thymeleaf'

 

* 기존 JSP와 다른 점은?

JSP: <form:inputText name="userName" value="${user.name}" />
Thymeleaf: <input type="text " name="userName" value="James Carrot" th:value="${user.name}" />

프론트엔드와 백엔드의 독립된 개발은 필수적이다.

jsp(jstl, el)를 사용하였을 때 만약 서버에서 처리해주지 않는다면 해당 태그가 제대로 표시되지 않는다.
반면 thymeleaf를 사용 할 경우 th: 로 시작하는 부분이 처리되지 않더라도 완벽하게 html input 태그의 형태를 가지고 있다.

HTML의 태그를 손대는 것이 아니라 HTML태그 내부의 어트리뷰트를 이용하여 구현할 수 있는 것!

 


* 적용해보기

 

model에 메세지를 넣고, resources/templates/hello.html에서 출력한다.

public class IndexController {       
   @GetMapping("/")        
   public String home(Model model) {        
     model.addAttribute("message", "hello world");       
     return "hello";         
   }
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8" />
</head>
<body>
  <div th:text="${message}">
  </div>
</body>
</html>

 


 

[참고1] https://www.thymeleaf.org/documentation.html

[참고2] https://blog.hanumoka.net/2018/08/01/spring-20180801-spring-Thymeleaf/#%EC%8B%A4%EC%8A%B5%ED%99%98%EA%B2%BD