Spring
API
Thymeleaf

Thymeleaf

Thymeleaf란?

서버 사이드 템플릿 엔진이다. 과거에는 JSP를 많이 사용했지만, 최근에는 공식적으로 Spring이 Thymeleaf를 권장하면서 Thymeleaf를 많이 사용한다.
JSP와는 다르게 서버 사이드 렌더링을 하지 않고 클라이언트 사이드 렌더링을 한다.

사용방법

  1. RestController가 아닌 Controller를 사용한다.
  2. templates 폴더 하위 폴더에서 탐색을 한다. 만약에 templates/ex/ex01.html을 호출하고 싶다면 return ex/ex01을 해주면 된다.
  3. model.addAttribute를 통해서 값을 넘겨준다. 이 때, 값은 key value 형식으로 넣어준다고 생각하면 된다.

예시

addAttribute를 통해서 data에 hello라는 값을 주고 GetMapping을 해줬으니 localhost:8080/hello라는 주소를 입력하면

@Controller
public class HelloController {
 
  @GetMapping("hello")
  public String hello(Model model) {
    /// data 라는 이름으로 hello!! 라는 값을 넘긴다.
    model.addAttribute("data", "hello!!");
    /// hello 라는 템플릿을 가서 찾아라
    return "hello";
  }
}

hello.html을 찾아서 렌더링을 해주게 되고 thymeleaf를 통해서 data라는 값을 넘겨주게 된다.

templates/hello.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>

Layout * Bootstrap

https://github.com/rookedsysc/shoppingmall/issues/7 (opens in a new tab)

Spring Security 얹기

Thymeleaf Spring Security 의존성을 추가한다.

build.gradle
implementation group: 'org.thymeleaf.extras', name: 'thymeleaf-extras-springsecurity5', version: '3.0.4.RELEASE'

html 파일에 다음과 같이 네임스페이스를 추가하면,

resources/templates/main.html
<html lang="kor" xmlns:th="http://www.thymeleaf.org">
 
...
<body> 
  <h1 th:text="${#authentication.name}"></h1>
</body>

Spring Security에서 제공하는 authentication 객체를 사용할 수 있다.
위에서 참조하는 객체 👇

public interface Authentication extends Principal, Serializable {}