2 분 소요


코드의 일부만 정리해 놓았다..

상품 목록 - Thymeleaf

BasicItemController

@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));
    }
}
  • @RequiredArgsConstructor
    • final이 붙은 멤버변수만 사용해서 생성자를 자동으로 만들어준다.

테스트용 데이터

  • @PostConstruct: 해당 빈의 의존관계가 모두 주입되고 나면 초기화 용도로 호출.
@Autowired
public BasicItemController(ItemRepository itemRepository) {
    this.itemRepository = itemRepository;
}
  • 생성자가 1개만 있으면 스프링이 해당 생정자에 Autowired로 의존관계를 주입해준다.


HTML 파트

/resources/templates/basic/items.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <link href="../css/bootstrap.min.css"
    th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
</head>

타임리프 사용 선언
<html xmlns:th="http://www.thymeleaf.org">

속성 변경 - th:href
th:href="@{/css/bootstrap.min.css}"

  • href="value1"th:href="value2"의 값으로 변경한다.
  • HTML을 그대로 볼 때는 href 속성이 사용되고, 뷰 템플릿을 거치면 th:href 의 값이 href 로 대체되면서 동적으로 변경할 수 있다.
  • 대부분의 HTML 속성을 th:xxx 로 변경할 수 있다.

상품등록(add)

<button class="btn btn-primary float-end" 
            onclick="location.href='addForm.html'"
            th:onclick="|location.href='@{/basic/items/add}'|"
            type="button">상품 등록</button>

속성 변경 - th:onclick

  • onclick="location.href='addForm.html'"
  • th:onclick="|location.href='@{/basic/items/add}'|"

리스트 출력

<tr th:each="item : ${items}">
    <td><a href="item.html" th:href="@{/basic/items/{itemId}(itemId=${item.id})}"
        th:text="${item.id}">회원id</a></td>

    <td><a href="item.html" 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>

반복 출력 - th:each

  • <tr th:each="item : ${items}">
  • 반복은 th:each를 사용. 이렇게 하면 모델에 포함된 items 컬렉션 데이터가 item변수에 하나씩 포함되고, 반복문 안에서 item변수를 사용할 수 있다.
  • 컬렉션의 수 만큼 <tr>..</tr> 생성

Thymeleaf 핵심

  • th:xxx가 붙은 부분은 서버사이드에서 렌더링되고, 기존 것을 대체한다.
  • HTML을 파일로 직접 열었을 때 th:xxx가 있어도 웹 브라우저는 th:속성을 알지 못하므로 무시.


URL 링크 표현식1 - @{…}
th:href="@{/css/bootstrap.min.css}"

  • 타임리프는 URL 링크를 사용하는 경우 @{...}를 사용한다.
  • URL 링크 표현식을 사용하면 서블릿 컨텍스트를 자동으로 포함한다.


URL 링크 표현식2 - @{…},

  • th:href="@{/basic/items/{itemId}(itemId=${item.id})}"
  • URL 링크 표현식을 사용하면 경로를 템플릿처럼 편리하게 사용할 수 있다.
  • 경로 변수({itemId}) 뿐만 아니라 쿼리 파라미터도 생성한다.
  • Ex) th:href="@{/basic/items/{itemId}(itemId=${item.id}, query='test')}"
    • 생성 링크: http://localhost:8080/basic/items/1?query=test


리터럴 대체 - |…|

  • 타임리프에서 문자와 표현식 등은 분리되어 있기 때문에 더해서 사용해야 한다.
    • 결과 : location.href='/basic/items/add'
    • 기존 : th:onclick="'location.href=' + '\'' + @{/basic/items/add} + '\''"
    • 문법 : th:onclick="|location.href='@{/basic/items/add}'|"
  • 위와 같이 리터럴 대체 문법을 사용하면 더하기 없이 편리하게 사용할 수 있다.


변수 표현식 - ${…}

  • <td th:text="${item.price}">10000</td>
  • 모델에 포함된 값이나, 타임리프 변수로 선언한 값을 조회할 수 있다.
  • 프로퍼티 접근법을 사용한다.(item.getPrice())


내용 변경 - th:text

  • <td th:text="${item.price}">10000</td>
  • 내용의 값을 th:text의 값으로 변경한다.
  • 여기서는 10000을 ${item.price}의 값으로 변경한다

참고
JSP는 파일을 웹 브라우저에서 그냥 열게되면 JSP코드와 HTML이 섞여 정상적인 확인이 불가능 하기 때문에 오직 서버를 통해서 열어야 한다. 하지만 타임리프는 순수 HTML파일을 웹 브라우저에서 열어도 내용을 확인할 수 있고, 서버를 통해 뷰 템플릿을 거치면 동적으로 변경된 결과를 확인할 수 있다.
이렇게 순수 HTML을 그대로 유지하면서 뷰 템플릿도 사용할 수 있는 타임리프의 특징을 natural templates라 한다.


<출처 : 인프런 - 스프링 MVC 1편 : 백엔드 웹 개발 핵심 기술(김영한)>

댓글남기기