본문 바로가기

[Spring] MVC 패턴 웹 페이지 4 - 상품 상세 페이지

@xuv22025. 6. 25. 13:00

이전 글에 이어 상품 상세 컨트롤러와 뷰를 만들어본다.

 

[Spring] MVC 패턴 웹 페이지 3 - HTML, 그리고 Thymeleaf

HTML , CSS는 잘 몰라서 부트스트랩 프레임워크의 힘을 빌렸다..스프링 부트에서 정적 리소스로 쓰기 위해 부트 스트랩으로 받은 파일들은 /resources/static 영역에 모아 두었다.컨트롤러 생성이제 컨

bdisappointed.tistory.com


컨트롤러 수정

package hello.itemservice.web.basic;

import hello.itemservice.domain.item.Item;
import hello.itemservice.domain.item.ItemRepository;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
@RequestMapping("/basic/items")
@RequiredArgsConstructor // 생성자 만들어줌 + 생성자가 하나니까 AutoWired도 발생
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";
    }

    @GetMapping("/{itemId}") // 해당 URI로 들어오는 쿼리를 변수로 쓸 수 있다
    public String item(@PathVariable Long itemId, Model model) {
        Item item = itemRepository.findById(itemId);
        model.addAttribute("item", item);
        return "basic/item";
    }


    // 테스트용 데이터
    @PostConstruct
    public void init() {

        itemRepository.save(new Item("itemA", 10000, 10));
        itemRepository.save(new Item("itemB", 20000, 20));
        itemRepository.save(new Item("itemC", 30000, 30));
    }
}

경로 변수로 넘어온 상품 ID로 상품을 조회하고, 모델에 담아둘 수 있도록 컨트롤러를 수정했다.


상품 상세 뷰

<!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">
    <style>
        .container {
            max-width: 560px;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="py-5 text-center">
        <h2>상품 상세</h2>
    </div>

    <!-- 추가 -->
    <h2 th:if="${param.status}" th:text="'저장완료'"></h2>

    <div>
        <label for="itemId">상품 ID</label>
        <input type="text" id="itemId" name="itemId" class="form-control" value="1" th:value="${item.id}" readonly>
    </div>
    <div>
        <label for="itemName">상품명</label>
        <input type="text" id="itemName" name="itemName" class="form-control" value="상품A" th:value="${item.itemName}" readonly>
    </div>
    <div>
        <label for="price">가격</label>
        <input type="text" id="price" name="price" class="form-control" value="10000" th:value="${item.price}" readonly>
    </div>
    <div>
        <label for="quantity">수량</label>
        <input type="text" id="quantity" name="quantity" class="form-control" value="10" th:value="${item.quantity}" readonly>
    </div>
    <hr class="my-4">
    <div class="row">
        <div class="col">
            <button class="w-100 btn btn-primary btn-lg"
                    onclick="location.href='editForm.html'"
                    th:onclick="|location.href='@{/basic/items/{itemId}/edit(itemId=${item.id})}'|"
                    type="button">상품 수정</button>
        </div>
        <div class="col">
            <button class="w-100 btn btn-secondary btn-lg"
                    onclick="location.href='items.html'"
                    th:onclick="|location.href='@{/basic/items}'|"
                    type="button">목록으로</button>
        </div>
    </div>
</div> <!-- /container -->
</body>
</html>

이전과 같이 타임 리프 문법을 추가 했다.

그리고 각 상품 정보마다 value 필드를 모델로부터 가져올 수 있도록 th:value 필드와 ${}문법을 사용했다.

마지막으로는 버튼 링크를 바꿔주면 되는데, 이또한 th:문법을 사용해주면된다.


상품 상세는 그냥 모델의 데이터를 뿌려주기만 하면 되니까 간단했다.

xuv2
@xuv2 :: xuvlog

폭싹 늙었수다

목차