Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

개발자되기 프로젝트

[WebPage] Thymeleaf로 고치기 본문

인프런/[인프런] 스프링 MVC 1

[WebPage] Thymeleaf로 고치기

Seung__ 2021. 9. 17. 14:12

1. Controller


  • ItemRepository는 final로 선언.
  • 그리고 Constructor를 통해 주입받음. ->lombok 이용
  • 생성자가 딱 한개 있으면 @Autowired생략 가능.
@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";
    }

    /**
     * Test용 Data
     */
    @PostConstruct
    public void init(){
        itemRepository.save(new Item("itemA", 10000, 10));
        itemRepository.save(new Item("itemB", 20000, 20));
    }
}

 

2. Thymeleaf로 변경하기


  • A라는 기능(?) 이  있을 경우 th:A라고 작성하면, Thymleaf에 의해 랜더링 되는 경우 A는 th:A로 대체됨.
  • HTML에서 Thymeleaf를 사용하기 위해서는 다음과 같인 선언? 필요 
    • <html xmlns:th="http://www.thymeleaf.org"> --> th로 사용
  • CSS 경로를 절대 경로로 변경
    • 기존 : 상대 경로 -> 기본적으로 해당 경로를 사용하나,
      <link href="../css/bootstrap.min.css" rel="stylesheet">
    • 변경 : 절대경로-> Thymeleaf에 의해 랜더링 되면 Thymleaf에서 설정한 경로 사용. 
    • 즉 Thymleaf가 기존 href를 th:href로 변경해버림. 
          <link th:href="@{/css/bootstrap.min.css}"
                  href="../css/bootstrap.min.css" rel="stylesheet">​
  • onclick시 경로 변경.
                <button class="btn btn-primary float-end"
                        onclick="location.href='addForm.html'"
                        th:onclick="|location.href='@{/basic/items/add}'|"
                        type="button">상품
                    등록</button>​
  • 루프 돌리기
    • Model로 넘어온 items에서 item하나씩 꺼냄.
      <tr th:each="item : ${items}">​
  • data 뿌리기
    • th:text를 사용하면 text위치에 동적으로 반영
    • 변경 전

                  <tr>
                      <td><a href="item.html">1</a></td>
                      <td><a href="item.html">테스트 상품1</a></td>
                      <td>10000</td>
                      <td>10</td>
                  </tr>
                  <tr>
                      <td><a href="item.html">2</a></td>
                      <td><a href="item.html">테스트 상품2</a></td>
                      <td>20000</td>
                      <td>20</td>
                  </tr>​
    • 변경 후
    • text들어갈 위치에 Thymleaf가 text 넣어줌.
    • Thymeleaf링크에 pathVariable 처럼 {itemId}와 같이 지정해주면 ()을 통해 해당 값을 동적으로 변경 가능.
    • th:href="@{basic/items/{itemId}(itemId=${item.id})}
      <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/{itemId}(itemId=${item.id})}"th:text="${item.itemName}">상품명</a></td>
          <td th:text="${item.price}">가격</td>
          <td th:text="${item.quantity}">수량</td>
      </tr>

 

 

3. Thymeleaf 정리


  • Thymeleaf 사용 선언 
    <html xmlns:th="http://www.thymeleaf.org">​
  • 속성 변경 - th:href
        <link th:href="@{/css/bootstrap.min.css}"
                href="../css/bootstrap.min.css" rel="stylesheet">​

    • href="value1"을 th:href="value2"로 변경
    • Thymleaf view template를 거치면 원래 값을 th:~~로 변경함. 만약 값이 없으면 새로 생성 ㅋㅋ
    • HTML을 그대로 볼 경우 href가 사용되고 view template를 거지면 th:href가 사용됨
    • HTML의  대부분 속성을 th:xxxx로 변경이 가능하다.
  • Thymleaf 핵심
    • th:xxx 부분은 Sever Side에서 랜더링 되고 기존 속성을 대체함.
    • th:xx 없으면 기존 속성 사용
    • HTML파일 그대로 열어도 브라우져는 th: 속성을 몰라서 처리 못함 기존 속성 사용함. ㅋㅋ
    • 즉 HTML파일 보기를 유지하면서 템플릿 기능도 할 수 있음 ㄱㅇㄷ
  • URL 링크 표현식 - @{...}
    th:href="@{/css/bootstrap.min.css}"​
    • @{...} : Thymleaf는 URL 링크 사용하는 경우 @{}를 사용해야함.
    • URL링크 표현식을 사용하면 Servlet Context 자동으로 포함함.->요즘 안씀.
  • 속성 변경- th:onclick
    onclick="location.href='addForm.html'"
    th:onclick="|location.href='@{/basic/items/add}'|"​
    •  literal 대체 문법 사용됨
  • literal 대체 - |...|
    • |...|
    • Thymleaf에서 문자와 표현식 등은 분리되어 있다. 따라서 더해서 사용해야함.
      • <span th:text="'Welcome to our application,' + ${user.name} + '!' "
    • 하지만 literal 대체 문법을 사용하면 더하기 없이 편하게 사용 가능
      • <span th:text="|Welcome to our application, ${user.name}!|"
    • <button class="btn btn-primary float-end"
        onclick="location.href='addForm.html'"
        th:onclick="|location.href='@{/basic/items/add}'|"
        type="button">상품 등록</button>​
  • 반복 출력 - th:each
    • <tr th:each="item = ${items}">
    • 반복은 th:each를 사용.
    •  collection 수 만큼 <tr>..</tr>태그 포함하여 생성됨.
  • 변수 표현식 - ${...}
    • <td th:text="${item.price}">10000</td>
    • Model에 포함된 값이나, Thymleaf 변수로 선언한 값을 조회 가능.
    • property 접근법 사용. (item.getPrice())
  • 내용 변경 - th:text
    • <td th:text="${item.price}">10000</td>
    • 내용의 값을 th:text의 갑으로 변경함.
    • 10000을 ${item.price} 값으려 변경
  • URL 링크 표현식2 - @{...}
    • th:href="@{/basic/items/{itemId}(itemId=${item.id})}"
    • url 링크 표현식을 사용하면 경로를 템플릿처럼 편리하게 사용 가능.
      • 근데 그냥...바로 ${item.id}쓰면 안되나..?->됨 literal대체
    • pathVariable(itemId), QueryParam도 생성 가능.
    • 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 파일을 웹브라우저에서 열어도 내용 확인 간으.
    • 서버를 통해 view template을 거치면 동적으로 변경된 결과도 확인 가능.
    • 이렇게 순수 HTML을 유지하면서 view template도 사용할 수 있는 thymeleaf의 특징을
    • natural template라고 함.

 

4. GitHub : 210917 Thymeleaf


 

GitHub - bsh6463/MVC3

Contribute to bsh6463/MVC3 development by creating an account on GitHub.

github.com

 

Comments