package hello.itemservice.web.basic;
import hello.itemservice.domain.item.Item;
import hello.itemservice.domain.item.ItemRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.PostConstruct;
import java.util.List;
@Controller
@RequestMapping("/basic/items")
@RequiredArgsConstructor
public class BasicItemController {
private final ItemRepository itemRepository;
@GetMapping
public String items(Model model) {
List<Item> items = itemRepository.findAll();
model.addAttribute("items", items);
return "basic/items";
}
@PostConstruct
public void init() {
itemRepository.save(new Item("testA", 10000, 10));
itemRepository.save(new Item("testB", 20000, 20));
}
}
컨트롤러 로직은 itemRepository에서 모든 상품을 조회한 다음에 모델에 담는다. 그리고 뷰 템플릿을 호출한다.
@RequiredArgsConstructor
final
이 붙은 멤버변수만 사용해서 생성자를 자동으로 만들어준다. public BasicItemController(ItemRepository itemRepository){
this.itemRepository = itemRepository;
}
테스트용 데이터 추가
@PostConstruct
: 해당 빈의 의존관계가 모두 주입되고 나면 초기화 용도로 호출된다.items.html 정적 HTML을 뷰 템플릿(templates) 영역으로 복사하고 다음과 같이 수정하자
/resources/static/items.html
-> 복사 -> /resources/templates/basic/items.html
/resources/templates/basic/items.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymelear.org">
<head>
<meta charset="utf-8">
<link th:href="@{/css/bootstrap.min.css}"
href="../css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container" style="max-width: 600px">
<div class="py-5 text-center">
<h2>상품 목록</h2>
</div>
<div class="row">
<div class="col">
<button class="btn btn-primary float-end"
th:onclick="|location.href='@{/basic/items/add}'|"
onclick="location.href='addForm.html'" type="button">상품
등록</button>
</div>
</div>
<hr class="my-4">
<div>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>상품명</th>
<th>가격</th>
<th>수량</th>
</tr>
</thead>
<tbody>
<tr th:each="item : ${items}">
<td>
<a th:href="@{/basic/items/{itemId}(itemId=${item.id})}"
th:text="${item.id}">회원id</a>
</td>
<td>
<a th:href="@{|/basic/items/${item.id}|}"
th:text="${item.itemName}">상품명</a>
</td>
<td th:text="${item.price}">10000</td>
<td th:text="${item.quantity}">10</td>
</tr>
</tbody>
</table>
</div>
</div> <!-- /container -->
</body>
</html>
타임리프 사용 선언
<html xmlns:th="http://www.thymeleaf.org">
속성 변경 - th:href
th:href="@{/css/bootstrap.min.css}"
href="value1"
을 th:href="value2"
의 값으로 변경한다.th:xxx
값으로 변경한다. 만약 값이 없다면 새로 생성한다.href
속성이 사용되고, 뷰 템플릿을 거치면 th:href 의 값이 href 로 대체되면서 동적으로 변경할 수 있다.th:xxx
로 변경할 수 있다.타임리프 핵심
th:xxx
가 붙은 부분은 서버사이드에서 렌더링 되고, 기존 것을 대체한다. th:xxx
이 없으면 기존 html의 xxx
속성이 그대로 사용된다.th:xxx
가 있어도 웹 브라우저는 th:
속성을 알지 못하므로 무시한다.URL 링크 표현식 - @{...}
th:href="@{/css/bootstrap.min.css}"
@{...}
: 타임리프는 URL 링크를 사용하는 경우 @{...}
를 사용한다. 이것을 URL 링크 표현식이라 한다.상품 등록 폼으로 이동
속성 변경 - th:onclick
onclick="location.href='addForm.html'"
th:onclick="|location.href='@{/basic/items/add}'|"
리터럴 대체 - |...|
|...|
:이렇게 사용한다.
<span th:text="'Welcome to our application, ' + ${user.name} + '!'">
<span th:text="|Welcome to our application, ${user.name}!|">
location.href='/basic/items/add'
th:onclick="'location.href=' + '\'' + @{/basic/items/add} + '\''"
th:onclick="|location.href='@{/basic/items/add}'|"
반복 출력 - th:each
<tr th:each="item : ${items}">
th:each
를 사용한다. 이렇게 하면 모델에 포함된 items
컬렉션 데이터가 item
변수에 하나씩 포함되고, 반복문 안에서 item
변수를 사용할 수 있다.<tr>..</tr>
이 하위 테그를 포함해서 생성된다.변수 표현식 - ${...}
<td th:text="${item.price}">10000</td>
( item.getPrice() )
내용 변경 - th:text
<td th:text="${item.price}">10000</td>
th:text
의 값으로 변경한다.${item.price}
의 값으로 변경한다.URL 링크 표현식2 - @{...}
th:href="@{/basic/items/{itemId}(itemId=${item.id})}"
{itemId}
) 뿐만 아니라 쿼리 파라미터도 생성한다.th:href="@{/basic/items/{itemId}(itemId=${item.id}, query='test')}"
http://localhost:8080/basic/items/1?query=test
URL 링크 간단히
th:href="@{|/basic/items/${item.id}|}"
참고
타임리프는 순수 HTML 파일을 웹 브라우저에서 열어도 내용을 확인할 수 있고, 서버를 통해 뷰 템플릿을 거치면 동적으로 변경된 결과를 확인할 수 있다. JSP를 생각해보면, JSP 파일은 웹 브라우저에서 그냥 열면 JSP 소스코드와 HTML이 뒤죽박죽 되어서 정상적인 확인이 불가능하다. 오직 서버를 통해서 JSP를 열어야 한다.
이렇게 순수 HTML을 그대로 유지하면서 뷰 템플릿도 사용할 수 있는 타임리프의 특징을 네츄럴 템플릿 (natural templates)이라 한다