Spring Boot와 JPA 활용1 - TIL(7)

45440 단어 Spring bootTILJPAJPA

[ 참고 강의 ] 실전! 스프링 부트와 JPA 활용1 - 웹 애플리케이션 개발

💡 웹 계층 개발

✏️ 상품 주문

상품 주문 컨트롤러


@Controller
@RequiredArgsConstructor
public class OrderController {

    private final OrderService orderService;
    private final MemberService memberService;
    private final ItemService itemService;

    @GetMapping("/order")
    public String createForm(Model model) {

        List<Member> members = memberService.findMembers();
        List<Item> items = itemService.findItems();

        model.addAttribute("members", members);
        model.addAttribute("items", items);

        return "order/orderForm";
    }

    @PostMapping("/order")
    public String order(@RequestParam("memberId") Long memberId,
                        @RequestParam("itemId") Long itemId,
                        @RequestParam("count") int count) {
        orderService.order(memberId, itemId, count);
        return "redirect:/orders";
    }
}

주문 폼 이동

  • 메인 화면에서 상품 주문을 선택하면 /order를 GET 방식으로 호출
  • OrderController의 createForm() 메서드
  • 주문 화면에는 주문할 고객정보와 상품 정보가 필요하므로 model 객체에 담아서 뷰에 넘겨줌

주문 실행

  • 주문할 회원과 상품 그리고 수량을 선택해서 submit 버튼을 누르면 /order URL을 POST 방식으로 호출
  • 컨트롤러의 order() 메서드를 실행
  • 이 메서드는 고객 식별자(memberId), 주문할 상품 식별자(itemId), 수량(count) 정보를 받아서 주문 서비스에 주문을 요청
  • 주문이 끝나면 상품 주문 내역이 있는 /orders URL로 리다이렉트

상품 주문 폼 orderForm

<!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 role="form" action="/order" method="post">
        <div class="form-group">
            <label for="member">주문회원</label>
            <select name="memberId" id="member" class="form-control">
                <option value="">회원선택</option> <option th:each="member : ${members}"
                                                       th:value="${member.id}"
                                                       th:text="${member.name}" />
            </select>
        </div>
        <div class="form-group">
            <label for="item">상품명</label>
            <select name="itemId" id="item" class="form-control"> <option value="">상품선택</option>
                <option th:each="item : ${items}"
                        th:value="${item.id}"
                        th:text="${item.name}" />
            </select>
        </div>
        <div class="form-group">
            <label for="count">주문수량</label>
            <input type="number" name="count" class="form-control" id="count"
                   placeholder="주문 수량을 입력하세요"> </div>
        <button type="submit" class="btn btn-primary">Submit</button>
    </form>
    <br/>
    <div th:replace="fragments/footer :: footer" />
</div> <!-- /container -->
</body>
</html>

✏️ 주문 목록 검색, 취소

주문 목록 검색 컨트롤러

    @GetMapping("/orders")
    public String orderList(@ModelAttribute("orderSearch") OrderSearch orderSearch, Model model) {
        List<Order> orders = orderService.findOrders(orderSearch);
        model.addAttribute("orders", orders);

        return "order/orderList";
    }

주문 목록 검색 화면 orderList

<!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>
        <div>
        <form th:object="${orderSearch}" class="form-inline">
            <div class="form-group mb-2">
                <input type="text" th:field="*{memberName}" class="form-control" placeholder="회원명"/>
            </div>
            <div class="form-group mx-sm-1 mb-2">
                <select th:field="*{orderStatus}" class="form-control">
                    <option value="">주문상태</option>
                    <option th:each=
                                    "status : ${T(jpabook.jpashop.domain.OrderStatus).values()}"
                            th:value="${status}"
                            th:text="${status}">option
                    </option>
                </select>
            </div>
            <button type="submit" class="btn btn-primary mb-2">검색</button>
        </form>
    </div>
        <table class="table table-striped">
            <thead>
            <tr>
                <th>#</th>
                <th>회원명</th>
                <th>대표상품 이름</th>
                <th>대표상품 주문가격</th>
                <th>대표상품 주문수량</th>
                <th>상태</th>
                <th>일시</th>
                <th></th>
            </tr>
            </thead>
            <tbody>
            <tr th:each="item : ${orders}">
                <td th:text="${item.id}"></td>
                <td th:text="${item.member.name}"></td>
                <td th:text="${item.orderItems[0].item.name}"></td>
                <td th:text="${item.orderItems[0].orderPrice}"></td>
                <td th:text="${item.orderItems[0].count}"></td>
                <td th:text="${item.status}"></td>
                <td th:text="${item.orderDate}"></td>
                <td>
                    <a th:if="${item.status.name() == 'ORDER'}" href="#"
                       th:href="'javascript:cancel('+${item.id}+')'"
                       class="btn btn-danger">CANCEL</a>
                </td>
            </tr>
            </tbody>
        </table>
    </div>
    <div th:replace="fragments/footer :: footer"/>
</div> <!-- /container -->
</body>
<script>
    function cancel(id) {
        var form = document.createElement("form");
        form.setAttribute("method", "post");
        form.setAttribute("action", "/orders/" + id + "/cancel");
        document.body.appendChild(form);
        form.submit();
}
   </script>
</html>

주문 취소

    @PostMapping("/orders/{orderId}/cancel")
    public String cancelOrder(@PathVariable("orderID") Long orderId) {
        orderService.cancelOrder(orderId);
        return "redirect:.orders";
    }

좋은 웹페이지 즐겨찾기