I T H

[프로젝트] 19. 장바구니 화면 (Week 4) 본문

Spring ArtGallery Project

[프로젝트] 19. 장바구니 화면 (Week 4)

thdev 2024. 1. 24. 09:48

앞서 상품페이지에서 장바구니에 담은 리스트를 보여주는

장바구니 리스트 화면 구현.

 

아래 3개의 테이블을 조인하여 데이터를 조회 

상품정보 테이블
상품이미지정보 테이블
장바구니 테이블 

 

[ cart.jsp ]

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
	
<!DOCTYPE html>
<html lang="kr">

<head>
    <meta charset="UTF-8">
    <meta name="description" content="">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- The above 4 meta tags *must* come first in the head; any other head content must come *after* these tags -->

    <!-- Title  -->
    <title>ART - 장바구니</title>

	<!-- import CSS -->
	<%@include file="/resources/inc/incCss.jsp"%>
</head>

<body>

    <!-- ##### Main Content Wrapper Start ##### -->
    <div class="main-content-wrapper d-flex clearfix">

        <!-- import Header -->
		<%@include file="/resources/inc/incHeader.jsp"%>
		
		<div class="cart-table-area section-padding-100">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-12 col-lg-8">
                        <div class="cart-title mt-50">
                            <h2>장바구니 리스트</h2>
                        </div>

                        <div class="cart-table clearfix">
                            <table class="table table-responsive">
                                <thead>
                                    <tr>
                                        <th></th>
                                        <th>상품명</th>
                                        <th>가격</th>
                                        <th>수량</th>
                                    </tr>
                                </thead>
                                <tbody id="mainTable">
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <div class="col-12 col-lg-4">
                        <div class="cart-summary">
                            <h5>장바구니 총합</h5>
                            <ul class="summary-table">
                                <li><span>합계:</span> <span id="sum">$140.00</span></li>
                                <li><span>배송비:</span> <span>Free</span></li>
                                <li><span>총합:</span> <span id="total">$140.00</span></li>
                            </ul>
                            <div class="cart-btn mt-100">
                                <a class="btn amado-btn w-100">결제하기</a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    </div>
    <!-- ##### Main Content Wrapper End ##### -->

    <!-- import Footer -->
	<%@include file="/resources/inc/incFooter.jsp"%>

    <!-- import JS -->
	<%@include file="/resources/inc/incJs.jsp"%>
	
	<!-- page script -->
	<script src="/resources/views/cart.js"></script>

</body>

</html>

 

[ cart.js ] 

/*******************************************************************************
 * cart.js
 * @author thkim
 * @since 2022
 * @DESC 장바구니 화면 스크립트
 ******************************************************************************/
(function() {
	
	function Cart() {
		
		/* 
		 * private variables
		 */
		var userId = "";
		
		/* 
		 * 초기화 메소드
		 */
		function _init() {
			// 이벤트 처리 함수 호출 
			bindEvent();
			
			// 세션에서 로그인한 사용자 아이디 가져오기
			findSessionInfo();
			
			// 로그인한 사용자의 장바구니 정보 조회
			findCartInfo();
		}
		
		function bindEvent() {
			
		}
		
		/*
		 * 세션에서 사용자 아이디 가져오기 
		 */
		function findSessionInfo() {
			var obj = {
			};
			
			// 로그인한 세션이 존재하는지 체크 후 아이디 정보를 가져온다. 
			cfFind("/findSession", obj, function(data) {
				userId = data.sessionId;
			}, true, "POST");
		} 
		
		/*
		 * 로그인한 사용자의 장바구니 정보 조회
		 */
		function findCartInfo() {
			
			var obj = {
				userId: userId
			};
			
			cfFind("/cart/findCartInfo", obj, function(data) {
				if(data.length > 0) {
					var html = "";
					var sumTotal = 0;
					$.each(data, function(idx, node) {
						
						sumTotal += (Number(node["PROD_PRICE"]) * Number(node["CART_CNT"]));
						
						html += "<tr>";
                        html += "    <td class='cart_product_img'>";
                        html += "        <a href='#'><img src='/resources/upload/" + node["PROD_IMG"] + "' alt='Product'></a>";
                        html += "    </td>";
                        html += "    <td class='cart_product_desc'>";
                        html += "        <h5>" + node["PROD_NAME"] + "</h5>";
                        html += "    </td>";
                        html += "    <td class='price'>";
                        html += "        <span>" + node["PROD_PRICE"] + "</span>";
                        html += "    </td>";
                        html += "    <td class='qty'>";
                        html += "        <div class='qty-btn d-flex'>";
                        html += "            <p>Qty</p>";
                        html += "            <div class='quantity'>";
                        html += "                <span class='qty-minus' onclick='var effect = document.getElementById('qty'); var qty = effect.value; if( !isNaN( qty ) &amp;&amp; qty &gt; 1 ) effect.value--;return false;'><i class='fa fa-minus' aria-hidden='true'></i></span>";
                        html += "                <input type='number' class='qty-text' id='qty' step='1' min='1' max='300' name='quantity' value='" + node["CART_CNT"] + "'>";
                        html += "                <span class='qty-plus' onclick='var effect = document.getElementById('qty'); var qty = effect.value; if( !isNaN( qty )) effect.value++;return false;'><i class='fa fa-plus' aria-hidden='true'></i></span>";
                        html += "            </div>";
                        html += "        </div>";
                        html += "    </td>";
                        html += "</tr>";
					});
					
					$("#mainTable").html(html);
					$("#sum").html(sumTotal);
					$("#total").html(sumTotal);
				} else {
					alert("장바구니 정보가 없습니다.");
					return;
				}
			}, true, "POST");
		}
		
		function _finalize() {
		}
		
		return {
            init : _init,
            finalize : _finalize
        };
    };
    
    var cart = new Cart();
    cart.init();
    
})();

//# sourceURL=cart.js

 

[ CartController.java ]

package kr.co.art.biz.cart.web;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import kr.co.art.biz.cart.persistence.CartMapper;

@Controller
@RequestMapping("/cart")
public class CartController {
	
	@Autowired
	private CartMapper cartMapper;
	
	@RequestMapping("")
	public String main() {
		return "cart";
	}
	
	/**
	 * 장바구니 리스트 조회
	 * (/cart/findCartInfo)
	 * @return
	 */
	@RequestMapping("/findCartInfo")
	@ResponseBody
	public List<Map<String, Object>> findCartInfo(@RequestBody Map<String, Object> param) {
		List<Map<String, Object>> list = cartMapper.findCartInfo(param);
		
		return list;
	}
	
}

 

[ CartMapper.java ]

package kr.co.art.biz.cart.persistence;

import java.util.List;
import java.util.Map;

public interface CartMapper {
	
	// 장바구니 리스트 조회
	List<Map<String, Object>> findCartInfo(Map<String, Object> params);
	
}

 

[ CartMapper.xml ]

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 
<mapper namespace="kr.co.art.biz.cart.persistence.CartMapper">

	<select id="findCartInfo" resultType="hashmap" parameterType="hashmap">
		SELECT A.CART_ID 
		     , A.USER_ID 
		     , A.CART_CNT 
		     , B.PROD_ID 
		     , B.PROD_IMG 
		     , C.PROD_NAME 
		     , C.PROD_PRICE 
		  FROM ART.ART_CART A 
		  LEFT OUTER JOIN ART.ART_PROD_DETAIL B 
		  ON A.PROD_ID = B.PROD_ID 
		  AND B.MAIN_IMG = 'Y'
		  LEFT OUTER JOIN ART.ART_PROD C
		  ON B.PROD_ID = C.PROD_ID
		 WHERE 1=1
		   AND A.USER_ID = #{userId}
	</select>
	
</mapper>