hyeonga_code

reProject_12_장바구니 기능 구현_1_장바구니 페이지 수정, 상품 선택 삭제, 전체 삭제 본문

Project_WEATHERWEAR

reProject_12_장바구니 기능 구현_1_장바구니 페이지 수정, 상품 선택 삭제, 전체 삭제

hyeonga 2023. 12. 29. 05:59
반응형

 

 

reProject_11_장바구니 페이지 구현

reProject_10_사용자 상품 상세 페이지 구현 reProject_09_사용자 상품 리스트 페이지 구현 2023.12.23 - [Project] - reProject_08_회원 정보 찾기 기능 구현(아이디 찾기, 비밀번호 찾기) 2023-12-22 -- 회원 기능을

hyeonga493.tistory.com

 

2023.12.28

- 상품 상세페이지에서 옵션 선택 후 장바구니에 담기 버튼 클릭 시 장바구니로 이동하며 장바구니 테이블에 데이터 삽입

- 옵션 선택 전 장바구니에 담기 페이지 클릭 시 alert 띄우기

 

>> 현재 작업해뒀던 js 파일, jsp 파일에서 div id를 proId로 설정하고 작업했으나, 같은 상품, 다른 옵션을 장바구니에 넣은 경우 중복되는 id값으로 몇가지 기능이 작동되지 않게되었다. 

>>> proId로 설정되어 있던 id값을 caId로 변경하는 작업을 하던 도중 caId는 mySql에서 auto_increment로 설정해두어 숫자로 이루어져 있어 "#${ caId }"를 읽어오는 데에 오류가 발생 > jsp와 js를 대대적으로 변경하게 되었다.

 

-- 장바구니 페이지 수정, 상품 선택 삭제, 전체 삭제 

1. client_cart.jsp 수정

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>WEATHERWEAR</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="/w2/resources/client/client_js/client_cart.js"></script>
    <link rel="stylesheet" href="/w2/resources/client/client_css/client_base_style.css">
    <link rel="stylesheet" href="/w2/resources/client/client_css/client_cart_style.css">
</head>
<body>
    <div class="container">
        <%@ include file="/WEB-INF/views/client/base/client_header.jspf" %>
        <div class="body">
                <div class="cartList">
                    <h2>CART</h2>
                    <div class="cart_table">
                        <ul class="cart_header">
                            <li class="cart_head no">
                                <input type="checkbox" id="checkAll" name="checkAll">
                                <label for="checkAll"></label>
                            </li>
                            <li class="cart_head con">PRODUCT</li>
                            <li class="cart_head count">COUNT</li>
                            <li class="cart_head price">PRICE</li>
                        </ul>
                    <c:forEach var="pro" items="${ cartList }">
    <!-- 상품마다 반복 시작 -->
                        <ul class="cart_content checklist">
                            <li class="cart_con no">
                                <input type="checkbox" name="checkbox" id="checkbox_${ pro.caId }" class="check" value="${ pro.caId }">
                                <label for="checkbox_${ pro.caId }"></label>
                            </li>
                            <li class="cart_con con">
                                <div class="product_info_div">
                                <section class="product_image_section">
                                    <img class="product_image" src="${ pro.provo.imvo.imageDir }${ pro.provo.imvo.imageName }" onclick="location.href='clientProductInfo.do?proId=${ pro.proId }'">
                                </section>
                                <section class="product_content_section">
                                    <span class="order_product_name">
                                        <a href="clientProductInfo.do?proId=${ pro.proId }" class="community_a">
                                            ${ pro.provo.proName }
                                        </a>
                                    </span>
                                    <span class="order_product_option">
                                        ${ pro.opvo.opColor } / ${ pro.opvo.opSize }
                                    </span>
                                </section>
                                </div>
                            </li>
                            <li class="cart_con count">
                                <div id="div_${ pro.caId }" class="cartValue">
                                    <button type="button" class="pro_btn" onclick="count(2,'${ pro.caId }')">-</button>
                                    <input class="pro_btn" name="${ pro.caId }" value="${ pro.caCnt }">
                                    <button type="button" class="pro_btn" onclick="count(1,'${ pro.caId }')">+</button>
                                    <input type="hidden" name="oriPrice_${ pro.caId }" value="${ pro.provo.pricevo.proPrice }">
                                </div>
                            </li>
                            <li class="cart_con price">
                                <div id="price_${ pro.caId }">
                    <!-- 상품가격*수량 합계 출력 -->
                                    <span id="totalPrice_${ pro.caId }" class="pro_totalPrice"></span>
                    <!-- 상품가격*수량 합계 -->
                                    <input type="hidden" name="totalPrice_${ pro.caId }">
                                </div>
                            </li>
                        </ul>
    <!-- 상품마다 반복 끝 -->
                    </c:forEach>
 
    <!-- 삭제 버튼 -->
                        <div class="cart_btn_div delete_btn">
                            <input type="button" id="addWishList" class="cart_btn" value="관심상품으로 이동">
                            <input type="button" id="deleteSelected" class="cart_btn" value="선택 삭제" onclick="deleteSelect()">
                            <input type="button" id="deleteAll" class="cart_btn" value="전체 삭제" onclick="deleteAll()">
                        </div>
                    </div>
                    <div class="cart_table_option">
    <!-- 금액 -->
                        <div class="cart_total">
                            <ul class="cart_total_ul">
                                <li class="cart_total_li"><span>총 상품금액</span></li>
                                <li class="cart_total_li val">
                                    <span id="totalPrice"></span>
                                    <input type="hidden" name="totalPrice">
                                </li>
                            </ul>
                            <ul class="cart_total_ul buho">
                                <li class="cart_total_buho">+</li>
                            </ul>
                            <ul class="cart_total_ul">
                                <li class="cart_total_li"><span>총 배송비</span></li>
                                <li class="cart_total_li val">
                                    <span id="deliPrice"></span>
                                    <input type="hidden" name="deliPrice">
                                </li>
                            </ul>
                            <ul class="cart_total_ul buho">
                                <li class="cart_total_buho">=</li>
                            </ul>
                            <ul class="cart_total_ul">
                                <li class="cart_total_li"><span>결제 예정 금액</span></li>
                                <li class="cart_total_li val">
                                    <span id="endPrice"></span>
                                    <input type="hidden" name="endPrice">
                                </li>
                            </ul>
                        </div>
    <!-- 주문 버튼 -->
                        <div class="cart_btn_div order_btn">
                            <input type="button" id="orderSelected" class="cart_btn" value="선택 상품 주문">
                            <input type="button" id="orderAll" class="cart_btn" value="전체 상품 주문">
                        </div>
                    </div>
                </div>                
        </div>
        <%@ include file="/WEB-INF/views/client/base/client_footer.jspf" %>
    </div>
</body>
</html>

 

 

2. client_cart_js 수정

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
// 가격 지정
$(document).ready(function(){
    setPrice();
});
 
// ajax_상품 삭제
function delProduct(caId){
    $.ajax({
        url: "/w2/clientDeleteCart.do",
        type: "POST",
        async: true,
        dataType: "text",
        data: JSON.stringify({
            caId : caId
        }),
        contentType: "application/json",
        success: function(result){
            // 상단에 모달창으로 보여지기?
        },
        error : function(error){
            alert("ajax는 실패입니다.");
        }
    });
}
 
// 선택 상품 삭제
function deleteSelect(){
    // 선택된 상품 없는 경우
    if(deleteList.length == 0){
        alert("삭제할 상품을 선택해주세요");
        return;
    }
    
    let caIdDiv;
    deleteList.forEach(check => {
        caIdDiv = document.querySelector("#div_"+check);
        caIdDiv.closest(".cart_content.checklist").remove();
        delProduct(check);
    });
    
    checkList.splice(0, checkList.length);
    deleteList.splice(0, deleteList.length);
    
    checkCounts = document.querySelectorAll(".check");
    setPrice();
}
 
// 전체 상품 삭제
function deleteAll(){
    checkCounts = document.querySelectorAll(".check");
    let caIdDiv;
    
    // 선택된 상품 없는 경우
    checkNone(deleteList);
    
    checkCounts.forEach(check => {
        caIdDiv = document.querySelector("#div_"+check.value);
        caIdDiv.closest(".cart_content.checklist").remove();
        delProduct(check.value);
    });
    checkList.splice(0, checkList.length);
    deleteList.splice(0, deleteList.length);
    
    checkCounts = document.querySelectorAll(".check");
    setPrice();
}
 
// 체크박스 적용
$(function(){
    $("#checkAll").click(function(){
        $(".check").prop("checked"this.checked);
        checkCounts = document.querySelectorAll(".check");
        
        if(this.checked){
            checkCounts.forEach((check, index) => {
                pushList(checkList, check.value);
                pushList(deleteList, check.value);
            });
        } else {
            checkCounts.forEach(check => {
                spliceList(checkList, check.value);
                spliceList(deleteList, check.value);
            });
        }
        setPrice();
    });
    
    $(".check").click(function(){
        
        if(this.checked){
            // 첫 화면시 모두 추가되어 있는 상태
            if(checkList.length == $(".checklist .check").length){
                checkList.splice(0, checkList.length);
            }
            
            pushList(checkList, this.value);
            pushList(deleteList, this.value);
        } else {
            spliceList(checkList, this.value);
            spliceList(deleteList, this.value);
        }
        
        if($(".check:checked").length < $(".checklist .check").length){
            $("#checkAll").prop("checked"false);
        } else {
            $("#checkAll").prop("checked"true);
        }
        setPrice();
    });
});
 
// checkList/deleteList 에 추가
function pushList(list, Value){
    const index = list.indexOf(Value);
    
    // 인덱스에 없는 경우
    if(index == -1){
        list.push(Value);
    }
}
 
// checkList/deleteList 에서 제거
function spliceList(list, Value) {
    const index = list.indexOf(Value);
 
    // 인덱스에 있는 경우
    if(index !== -1){
        list.splice(index, 1);
    }
}
 
// list 상태 확인
function checkNone(list){
    if(list == ''){
        // 상품별 count li 태그 찾기
        const cartCounts = document.querySelectorAll(".cart_con.count");
        cartCounts.forEach(cartId => {
            list.push((cartId.querySelector(".cartValue").id).split("_")[1]);
        });
    }
}
 
// 값 설정
function setPrice(){
    let totalPriceVal = 0;
    let deliPriceVal = 3000;
 
    checkNone(checkList);
    
    // 상품별
    checkList.forEach(check => {
        const caId = check;
 
        // 수량
        const countInput = document.querySelector("input[name='" + caId + "']");
        
        // 기본 가격
        const oriPriceInput = document.querySelector("input[name='oriPrice_" + caId + "']");
        
        const priceDiv = document.querySelector("#price_" + caId);
        const pro_totalPriceSpan = priceDiv.querySelector("#totalPrice_" + caId);
        const pro_totalPriceInput = priceDiv.querySelector("input");
        
        // (기본가격 * 수량)
        let pro_totalPrice = countInput.value * oriPriceInput.value
        
        pro_totalPriceSpan.innerHTML = setFormat(pro_totalPrice);
        pro_totalPriceInput.value = pro_totalPrice;
 
        // 총 상품 금액
        totalPriceVal += pro_totalPrice;                
    });
    
    // 배송비 조건부 무료
    if(totalPriceVal > 50000 || totalPriceVal == 0){
        deliPriceVal = 0;
    }
 
    // input
    const totalPriceInput = document.querySelector("input[name='totalPrice']");
    const deliPriceInput = document.querySelector("input[name='deliPrice']");
    const endPriceInput = document.querySelector("input[name='endPrice']");
    
    //span
    const totalPriceSpan = document.querySelector("#totalPrice");
    const deliPriceSpan = document.querySelector("#deliPrice");
    const endPriceSpan = document.querySelector("#endPrice");
    
    totalPriceInput.value = totalPriceVal;
    deliPriceInput.value = deliPriceVal;
    endPriceInput.value = totalPriceVal + deliPriceVal;
    
    totalPriceSpan.innerHTML = setFormat(totalPriceVal);
    deliPriceSpan.innerHTML = setFormat(deliPriceVal);
    endPriceSpan.innerHTML = setFormat(totalPriceVal + deliPriceVal);
}
 
let checkList = [];        // 주문 리스트
let deleteList = [];    // 삭제 리스트
 
// 체크박스 전체
let checkCounts = document.querySelectorAll(".check");
 
// 수량 증가
function count(num, name) {
    const countInput = document.querySelector("input[name='" + name + "']");
    const pro_oriPriceInput = document.querySelector("input[name='oriPrice_" + name + "']");
    const pro_totalPriceInput = document.querySelector("input[name='totalPrice_" + name + "']");
    const pro_totalPriceSpan = document.querySelector("#totalPrice_" + name);
 
    let cnt = parseInt(countInput.value);
    let pro_oriPrice = parseInt(pro_oriPriceInput.value);
    let pro_totalPrice = parseInt(pro_totalPriceInput.value);
    
    if (num == 1) { // 수량 증가
        pro_totalPrice += pro_oriPrice;
        cnt++;
    } else if (num == 2){ // 수량 감소
        pro_totalPrice -= pro_oriPrice;
        cnt--;
    }
    
    if(cnt < 1){
        alert("수량은 1개 이상이어야 합니다.");
        cnt = 1;
        pro_totalPrice = pro_oriPrice;
    }
    
    countInput.value = cnt;
    pro_totalPriceInput.value = pro_totalPrice;
    pro_totalPriceSpan.innerHTML = setFormat(pro_totalPrice);
    
    setPrice();
}
 
// 숫자 표기
function setFormat(num){
    let result = num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return result;
}

 

 

3. ClientGetController.java 수정

	/** 장바구니 */
	@RequestMapping("clientCart.do")
	public String cart(HttpServletRequest request, HttpSession session, Model model, ClientCartVO cartvo) {
		System.out.println("1. [ Client Get Controller ] cart");
		
		if((String)session.getAttribute("session") == null) {
			Cookie cookie = WebUtils.getCookie(request, "cartCookie");
			if (cookie != null) {
				System.out.println("비회원인데 장바구니는 있음");
				cartvo.setCkId((String)cookie.getValue());
			}
		} else {
			cartvo.setCaId((String)session.getAttribute("session"));
		}
		
		model.addAttribute("cartList", cartService.getClientCartList(cartvo));
		return "client_cart";
	}
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package com.w2.client.controller;
 
import java.util.HashMap;
import java.util.List;
 
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.util.WebUtils;
 
import com.w2.client.ClientService;
import com.w2.client.ClientVO;
import com.w2.client.cart.ClientCartService;
import com.w2.client.cart.ClientCartVO;
import com.w2.client.product.ClientProductService;
 
import lombok.extern.slf4j.Slf4j;
 
@Slf4j
@Controller
public class ClientGetController {
 
    @Autowired
    private ClientService clientService;
    
    @Autowired
    private ClientProductService productService;
    
    @Autowired
    private ClientCartService cartService;
    
    /** 사용자 메인페이지 */
    @RequestMapping("clientMain.do")
    public String main() {
        log.debug(null);
        return "client_main";
    }
    
    /** 상품 리스트 페이지 */
    @RequestMapping("clientProductList.do")
    public String clientProductList(@RequestParam(value = "page", required = false)Integer page, 
                                @RequestParam(value="ordertype", required=falseString ordertype, 
                                @RequestParam(value="gubun", required=false)String gubun, Model model) {
        System.out.println("1. [ Client Get Controller ] productList");
        
        HashMap<String, Object> check = new HashMap<String, Object>();
        if(page == null || page == 0) {
            check.put("page"1);
        } else {
            check.put("page", (int)page);
        }
        
        check.put("table""product");
        check.put("ordertype", (String)ordertype);
        check.put("gubun", (String)gubun);
        
        
        List<HashMap<String, Object>> productList = productService.clientProductList(check, model);
        
        model.addAttribute("productList", productList);
        
        return "client_productList";
    }
    
    /** 상품 상세 페이지 */
    @RequestMapping("clientProductInfo.do")
    public String clientProductInfo(@RequestParam(value = "proId", required = false)String proId, Model model) {
        System.out.println("1. [ Client Post Controller ] clientProductInfo");
        
        model.addAttribute("product", productService.clientProductInfo(proId));
        
        return "client_productInfo";
    }
    
    /** 사용자 로그인 페이지 */
    @RequestMapping("clientLogin.do")
    public String login() {
        return "client_login";
    }
 
    /** 로그아웃 요청 */
    @RequestMapping("clientLogout.do")
    public String logout(HttpSession session) {
        if(session != null) {
            session.invalidate();
        }
        return "redirect:/clientMain.do";
    }
    
    /** 사용자 정보 찾기 페이지 */
    @RequestMapping("clientFindInfo.do")
    public String findInfo() {
        return "client_findInfo";
    }
 
    /** 회원가입 페이지 */
    @RequestMapping("clientSignup.do")
    public String signup() {
        return "client_signup";
    }
    
    /** 커뮤니티 페이지 */
    @RequestMapping("clientCommunity.do")
    public String community() {
        return "client_community";
    }
    
    /** 마이페이지 */
    @RequestMapping("clientMypage.do")
    public String mypage(HttpSession session, ClientVO client, Model model) {
        System.out.println("1. [ Client Get Controller ] myPage ");
        
        if(session!=null) {
            HashMap<String, Object> myinfo = clientService.clientSetMypage((String)session.getAttribute("session"));
            model.addAttribute("myinfo", myinfo);
        }
        
        return "client_mypage";
    }
    
    /** 장바구니 */
    @RequestMapping("clientCart.do")
    public String cart(HttpServletRequest request, HttpSession session, Model model, ClientCartVO cartvo) {
        System.out.println("1. [ Client Get Controller ] cart");
        
        if((String)session.getAttribute("session"== null) {
            Cookie cookie = WebUtils.getCookie(request, "cartCookie");
            if (cookie != null) {
                System.out.println("비회원인데 장바구니는 있음");
                cartvo.setCkId((String)cookie.getValue());
            }
        } else {
            cartvo.setCaId((String)session.getAttribute("session"));
        }
        
        model.addAttribute("cartList", cartService.getClientCartList(cartvo));
        return "client_cart";
    }
}

 

 

>>> ClientPostController.java에 모든 기능을 작업하려니 너무 코드가 길어져 가독성이 떨어질 것 같아 Cart 관련 기능은

ClientCartController.java에 작성

 

 

4. ClientCartController .java 작성

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.w2.client.controller;
 
import java.io.IOException;
import java.util.Map;
 
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.util.WebUtils;
 
import com.w2.client.ClientService;
import com.w2.client.cart.ClientCartService;
import com.w2.client.cart.ClientCartVO;
import com.w2.util.RandomString;
 
@Controller
public class ClientCartController {
    
    @Autowired
    private ClientService clientService;
    
    @Autowired
    private ClientCartService cartService;
    
    /** 장바구니 상품 삭제 */
    @PostMapping("clientDeleteCart.do")
    public void clientDeleteCart(@RequestBody Map<StringString> data, HttpSession session, ClientCartVO cartvo, HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("1. [ Client Cart Controller ] clientAddCart");
        System.out.println((String)data.get("caId"));
        
        // 비로그인 상태인 경우
        if(session.getAttribute("session"== null) {
            Cookie cookie = WebUtils.getCookie(request, "cartCookie");
            String ckId = cookie.getValue();
                
            // 쿠키 세션 재설정
            cookie.setMaxAge(60*60*24*2);
            response.addCookie(cookie);
            
            cartvo.setCkId(ckId);
        } else { // 로그인 상태인 경우
            cartvo.setClientId((String)session.getAttribute("session"));
        }
        
        int result = cartService.clientDeleteCart((String)data.get("caId"));
 
        response.setContentType("application/json");
        response.getWriter().write(String.valueOf(result));
    }
}

 

 

5. ClientCartService.java 인터페이스 작성

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.w2.client.cart;
 
import java.util.List;
 
public interface ClientCartService {
 
    // 장바구니 목록 불러오기
    List<ClientCartVO> getClientCartList(ClientCartVO cartvo);
 
    // 장바구니 상품 삭제
    int clientDeleteCart(String string);
}
 

 

 

6. ClientCartServiceImpl.java 클래스 작성

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
32
33
34
package com.w2.client.cart.impl;
 
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import com.w2.client.cart.ClientCartDAO;
import com.w2.client.cart.ClientCartService;
import com.w2.client.cart.ClientCartVO;
 
@Service("cartService")
public class ClientCartServiceImpl implements ClientCartService {
 
    @Autowired
    private ClientCartDAO cartDAO;
    
    // 장바구니 목록 불러오기
    @Override
    public List<ClientCartVO> getClientCartList(ClientCartVO cartvo) {
        System.out.println("2. [ ClientCartService ] getClientCartList");
        
        return cartDAO.getClientCartList(cartvo);
    }
 
    // 장바구니 상품 삭제
    @Override
    public int clientDeleteCart(String caId) {
        System.out.println("2. [ ClientCartService ] clientDeleteCart");
        
        return cartDAO.clientDeleteCart(caId);
    }
}
 

 

7. CilentCartDAO.java 클래스 작성

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
package com.w2.client.cart;
 
import java.util.List;
 
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
 
@Repository
public class ClientCartDAO {
 
    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;
 
    // 장바구니 목록 불러오기
    public List<ClientCartVO> getClientCartList(ClientCartVO cartvo) {
        System.out.println("3. [ CartDAO ] getClientCartList");
 
        return sqlSessionTemplate.selectList("CartDAO.getClientCartList", cartvo);
    }
 
    // 장바구니 상품 삭제
    public int clientDeleteCart(String caId) {
        System.out.println("3. [ CartDAO ] clientDeleteCart");
 
        return sqlSessionTemplate.delete("CartDAO.clientDeleteCart", caId);
    }
}
 

 

 

 

>>> VO에서 다른 VO를 join용으로 가지고 있을 때 기존에는 작업을 어떻게 해야 할 지 모르겠어서 vo에 전부 때려넣고 작업을 했었다. resultMap에서 collection을 사용해서 다른 resultMap을 참조할 수 있는 방법을 사용해서 작업했다.

 

8. client-cart-mapping.xml 파일 작성

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<?xml version="1.0" encoding="UTF-8"?>
 
<!-- MyBatis 다운 파일 PDF 에서 붙여넣은 내용입니다. -->
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
                 
<mapper namespace="CartDAO">
    <resultMap type="com.w2.client.cart.ClientCartVO" id="clientCart">
        <id property="caId" column="caId" />
        <result property="proId" column="proId" />
        <result property="clientId" column="cId" />
        <result property="opId" column="opId" />
        <result property="caDate" column="caDate" />
        <result property="caCnt" column="caCnt" />
        <result property="ckId" column="ckId" />
        <result property="ckLimit" column="ckLimit" />
        
        <collection property="provo" resultMap="provoResult" />
        <collection property="opvo" resultMap="opvoResult" />
    </resultMap>
    
    <resultMap type="com.w2.product.ProductVO" id="provoResult">
        <result property="proId" column="proId" />
        <result property="proCate" column="proCate" />
        <result property="proName" column="proName" />
        <result property="proContent" column="proContent" />
        <result property="proRegDate" column="proRegDate" />
        <result property="proSell" column="proSell" />
        <result property="proCnt" column="proCnt" />
        <result property="proView" column="proView" />
        <result property="proLike" column="proLike" />
        
        <collection property="imvo" resultMap="imvoResult" />
        <collection property="pricevo" resultMap="pricevoResult" />
    </resultMap>
    
    <resultMap type="com.w2.product.ProductPriceVO" id="pricevoResult">
        <result property="proId" column="proId" />
        <result property="proPrimeCost" column="proPrimeCost" />
        <result property="proCost" column="proCost" />
        <result property="proPrice" column="proPrice" />
        <result property="proTax" column="proTax" />
        <result property="proMargin" column="proMargin" />
        <result property="proAddCost" column="proAddCost" />
    </resultMap>
    
    <resultMap type="com.w2.util.ImageVO" id="imvoResult">
        <result property="imageId" column="imageId" />
        <result property="imageName" column="imageName" />
        <result property="imageDir" column="imageDir" />
        <result property="imageStatus" column="imageStatus" />
        <result property="imageBy" column="imageBy" />
    </resultMap>
    
    <resultMap type="com.w2.product.OptionVO" id="opvoResult">
        <result property="proId" column="proId" />
        <result property="opColor" column="opColor" />
        <result property="opSize" column="opSize" />
        <result property="opId" column="opId" />
        <result property="stCnt" column="stCnt" />
    </resultMap>
    
<!-- 장바구니 목록 조회 -->
    <select id="getClientCartList" parameterType="clientCart" resultMap="clientCart">
        SELECT pro.proId, pro.proName, ca.opId,
                im.imageDir, im.imageName, 
                op.opColor, op.opSize, pri.proPrice, 
                ca.caCnt, ca.caId,
                <if test="clientId != null">
                    cId
                </if>
                <if test="clientId == null">
                    ckId
                </if>
        FROM cart ca
        LEFT JOIN product pro ON ca.proId = pro.proId
        LEFT JOIN product_image im ON ca.proId = im.imageBy AND im.imageStatus='대표'
        LEFT JOIN option_info op ON ca.opId = op.opId
        LEFT JOIN product_price pri ON ca.proId = pri.proId
        <where>
            <if test="clientId != null">
                cId = #{ clientId }
            </if>
            <if test="clientId == null">
                ckId = #{ ckId }
            </if>
        </where>
    </select>
    
<!-- 장바구니 상품 삭제 -->
    <delete id="clientDeleteCart" parameterType="String">
        DELETE FROM cart WHERE caId=#{ caId }
    </delete>    
</mapper>

 

 

9. mybatis-config.xml 파일에 추가

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
<?xml version="1.0" encoding="UTF-8"?>
 
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 
                "http://mybatis.org/dtd/mybatis-3-config.dtd">
 
<configuration>
    
    <typeAliases>
        <!-- typeAlias
                - 매핑파일에서 사용하는 type을 지정
                - 애플리케이션에서 SQL 문으로 값을 전달합니다
                - SQL 문 실행 시 반환되는 레코드를 저장하는 용도로 사용하기 위한 빈을 생성합니다.-->
        <typeAlias type="com.w2.client.ClientVO" alias="client" />
        <typeAlias type="com.w2.client.cart.ClientCartVO" alias="clientCart" />
        <typeAlias type="com.w2.product.ProductVO" alias="provo" />
        <typeAlias type="com.w2.product.ProductPriceVO" alias="pricevo" />
        <typeAlias type="com.w2.util.ImageVO" alias="imvo" />
        <typeAlias type="com.w2.product.OptionVO" alias="opvo" />
    </typeAliases>
 
    <!-- SQL 작성문을 지정하여 mapper 파일 경로 알려주는 역할입니다. -->
    <mappers>
        <mapper resource="mappings/client-mapping.xml" />
        <mapper resource="mappings/client-product-mapping.xml" />
        <mapper resource="mappings/client-cart-mapping.xml" />
    </mappers>
</configuration>

 

 

VO에 다른 VO를 추가하기 위해 필요한 VO 파일을 생성해야 했다.

-- com.w2.product 패키지 생성

---- OptionVO.java

package com.w2.product;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Getter
@Setter
@ToString
public class OptionVO {
	private String proId;	// 상품 번호
	private String opColor;	// 색상
	private String opSize;	// 사이즈
	private String opId;	// 옵션아이디
	private int stCnt;		// 재고수량
}

 

 

---- ProductPriceVO.java

package com.w2.product;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Getter
@Setter
@ToString
public class ProductPriceVO {
	private String proId;  		// 상품번호
	private int proPrimeCost;  	// 공급가
	private int proCost;  		// 소비자가
	private int proPrice;  		// 판매가
	private Double proTax;  	// 과세율
	private Double proMargin;  	// 마진율
	private int proAddCost;  	// 추가금액
}

 

 

---- 기존의 com.w2.client.product.ClientProductVO.java 파일을 ProductVO.java 파일로 변경

package com.w2.product;

import java.util.Date;
import com.w2.util.ImageVO;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Getter
@Setter
@ToString
public class ProductVO {
	 
	// product
	private String proId;  		// 상품번호
	private String proCate;		// 상품 카테고리
	private String proName;  	// 상품명
	private String proContent;  // 상세설명
	private Date proRegDate;  	// 등록일
	private String proSell;  	// 판매상태
	private int proCnt;  		// 판매량
	
	private int proView;  		// 조회수
	private int proLike;  		// 좋아요수
	
	// join용
	private ImageVO imvo;		// 이미지
	private ProductPriceVO pricevo;	// 상품가격
}

 

> ImageVO는 admin/client 에서 전부 사용할 예정이므로 util 패키지에 생성

-- com.w2.util 패키지

---- ImageVO.java

package com.w2.util;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Getter
@Setter
@ToString
public class ImageVO {
	private String imageId;		// 이미지 고유 번호
	private String imageName; 	// 이미지 이름
	private String imageDir;	// 이미지 저장 경로
	private String imageStatus;	// 이미지 상태(환불, 문의, 리뷰)
	private String who; 		// admin, client, product 구분
	private String imageBy; 	// client/admin : cId, product : proId
}

 

 

reProject_13_장바구니 기능 구현_2_상품 상세 페이지에서 장바구니에 추가 기능 구현

2023.12.29 - [Project] - reProject_12_장바구니 기능 구현_1_장바구니 페이지 수정, 상품 선택 삭제, 전체 삭제 2023.12.28 -- 상품 상세에서 장바구니에 추가 기능 구현 >> 비로그인 장바구니 기능을 구현하기

hyeonga493.tistory.com

 

반응형