[DMD] 6-2. 웹 개발 - Item

sorzzzzy·2021년 12월 18일
0

Spring Project

목록 보기
7/18
post-thumbnail

이번 시간에는 상품 관련 폼과 컨트롤러를 개발해보겠다.


🏷 상품 등록

✔️ 상품 등록 폼 - FoodForm

package sorzzzzy.dearmydog.controller;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class FoodForm {
    private Long id;

    private String name;
    private int price;
    private int stockQuantity;

    private String allowance;
    private String ingredient;
}

상품 등록은 이전 시간에 했던 회원 등록과 크게 다르지 않다.


✔️ 상품 등록 컨트롤러 - ItemController

package sorzzzzy.dearmydog.controller;

import sorzzzzy.dearmydog.domain.Item.Food;
import sorzzzzy.dearmydog.domain.Item.Item;
import sorzzzzy.dearmydog.service.ItemService;
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.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.List;

@Controller
@RequiredArgsConstructor
public class ItemController {

    private final ItemService itemService;

    // 상품 등록 - GET
    @GetMapping("/items/new")
    public String createForm(Model model) {
        model.addAttribute("form", new FoodForm());
        return "items/createItemForm";
    }

    // 상품 등록 - POST
    @PostMapping("/items/new")
    public String create(FoodForm form) {

        Food food = new Food();
        food.setName(form.getName());
        food.setPrice(form.getPrice());
        food.setStockQuantity(form.getStockQuantity());
        food.setAllowance(form.getAllowance());
        food.setIngredient(form.getIngredient());

        itemService.saveItem(food);
        return "redirect:/";
    }

컨트롤러 또한 마찬가지로, 크게 다르지 않다.
상품 등록 폼에서 데이터를 입력하고 Submit 버튼을 클릭하면 /items/newPOST 방식으로 요청하고,
상품 저장이 끝나면 상품 목록 화면(redirect:/items)으로 리다이렉트한다.


✔️ 상품 등록 뷰 - createItemForm.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="fragments/header :: header" />
<body>

<div class="container">
    <div th:replace="fragments/bodyHeader :: bodyHeader"/>

    <form th:action="@{/items/new}" th:object="${form}" method="post">
        <div class="form-group">
            <label th:for="name">상품명</label>
            <input type="text" th:field="*{name}" class="form-control" placeholder="이름을 입력하세요">
        </div>
        <div class="form-group">
            <label th:for="price">가격</label>
            <input type="number" th:field="*{price}" class="form-control" placeholder="가격을 입력하세요">
        </div>
        <div class="form-group">
            <label th:for="stockQuantity">수량</label>
            <input type="number" th:field="*{stockQuantity}" class="form-control" placeholder="수량을 입력하세요">
        </div>
        <div class="form-group">
            <label th:for="allowance">권장량</label>
            <input type="text" th:field="*{allowance}" class="form-control" placeholder="하루 권장량을 입력하세요">
        </div>
        <div class="form-group">
            <label th:for="ingredient">주재료</label>
            <input type="text" th:field="*{ingredient}" class="form-control" placeholder="들어가는 주재료를 입력하세요">
        </div>
        <button type="submit" class="btn btn-primary">Submit</button>
    </form>
    <br/>
    <div th:replace="fragments/footer :: footer" />

</div> <!-- /container -->


</body>
</html>

주의할 점은, PDF에서 html 파일을 복사할 때 줄바꿈 때문에 form-controlformcontrol 이라고 붙는 경우가 있다.
이 경우 form-control 로 수정해야 한다.


✔️ 상품 목록 컨트롤러 - ItemController

.
.
.
    // 상품 목록 조회
    @GetMapping("/items")
    public String list(Model model) {
        // findItems() 로 찾아온 뒤, modelAttribute 사용
        List<Item> items = itemService.findItems();
        model.addAttribute("items", items);
        return "items/itemList";
    }

✔️ 상품 목록 뷰 - itemList.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="fragments/header :: header" />
<body>

<div class="container">
    <div th:replace="fragments/bodyHeader :: bodyHeader"/>

    <div>
        <table class="table table-striped">
            <thead>
            <tr>
                <th>#</th>
                <th>상품명</th>
                <th>가격</th>
                <th>재고수량</th>
                <th></th>
            </tr>
            </thead>
            <tbody>
            <tr th:each="item : ${items}">
                <td th:text="${item.id}"></td>
                <td th:text="${item.name}"></td>
                <td th:text="${item.price}"></td>
                <td th:text="${item.stockQuantity}"></td>
                <td>
                    <a href="#" th:href="@{/items/{id}/edit (id=${item.id})}" class="btn btn-primary" role="button">수정</a>
                </td>
            </tr>
            </tbody>
        </table>
    </div>

    <div th:replace="fragments/footer :: footer"/>

</div> <!-- /container -->

</body>
</html>

model 에 담아둔 상품 목록인 items 를 꺼내서 상품 정보를 출력한다.


다음 시간에는 가장 중요한 상품 수정에 대해 다뤄보겠다.

profile
Backend Developer

0개의 댓글