hyeonga_code
reProject_13_장바구니 기능 구현_2_상품 상세 페이지에서 장바구니에 추가 기능 구현 본문
reProject_13_장바구니 기능 구현_2_상품 상세 페이지에서 장바구니에 추가 기능 구현
hyeonga 2023. 12. 29. 06:59
reProject_12_장바구니 기능 구현_1_장바구니 페이지 수정, 상품 선택 삭제, 전체 삭제
reProject_11_장바구니 페이지 구현 reProject_10_사용자 상품 상세 페이지 구현 reProject_09_사용자 상품 리스트 페이지 구현 2023.12.23 - [Project] - reProject_08_회원 정보 찾기 기능 구현(아이디 찾기, 비밀번
hyeonga493.tistory.com
2023.12.28
-- 상품 상세에서 장바구니에 추가 기능 구현
>> 비로그인 장바구니 기능을 구현하기 위해 cart 테이블을 수정했다. 회원용/비회원용으로 테이블을 따로 설정하는 방법도 있으나 비로그인 상태로 장바구니에 상품을 넣은 후 로그인 시 데이터를 옮겨야하는 번잡한 과정을 생략하기 위함이었다.
-- cId(회원번호) : NOT NULL >> NULL로 변경
-- ckId(쿠키번호) 추가
-- ckLimit(쿠키만료일) 추가가
---- 로그인한 경우 세션 정보를 cId에 저장
---- 비로그인인 경우 쿠키를 생성해서 ckId에 저장
---- 쿠키만료시 장바구니에서 자동 삭제
---- 같은 쿠키 번호로 된 데이터가 있는 경우 상품 추가시 쿠키 만료일자 변경
1. client_productInfo.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
|
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>WEATHERWEAR</title>
<script src="/w2/resources/client/client_js/client_productInfo.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_productInfo_style.css">
</head>
<body>
<div class="container">
<%@ include file="/WEB-INF/views/client/base/client_header.jspf" %>
<input type="hidden" name="proPrice" value="${ product.proPrice }">
<input type="hidden" name="proId" value="${ product.proId }">
<input type="hidden" name="proName" value="${ product.proName }">
<div class="body">
<div class="product_body">
<div class="product_info">
<div class="product_main_image">
<img class="main_image" src="${ product.imageDir }${ product.imageName }"><br>
</div>
<div class="product_info_detail">
<ul class="product_info_ul">
<li class="product_info_li productName">
${ product.proName }
</li>
<li class="product_info_li productPrice">
<fmt:formatNumber value="${ product.proPrice }" pattern="###,### 원"/>
</li>
<li class="product_info_li">
<label for="opColor" class="product_info_label">색상</label>
<select class="select" id="opColor" onchange="select(this)">
<option value="SELECT">선택</option>
<c:forEach var="color" items="${ product.colorList }">
<option value="${ color }">${ color }</option>
</c:forEach>
</select>
</li>
<li class="product_info_li">
<label for="opSize" class="product_info_label">사이즈</label>
<select class="select" id="opSize" onchange="select(this)">
<option value="SELECT">선택</option>
<c:forEach var="size" items="${ product.sizeList }">
<option value="${ size }">${ size }</option>
</c:forEach>
</select>
</li>
<li class="product_info_optionSelect">
<section class="total_price">
<ul class="product_form_ul">
<li class="product_form_th">
총 상품 금액 :
</li>
<li class="product_form_td">
<input type="number" name="odTotal" value="0" id="odTotal" disabled="disabled">원
</li>
</ul>
</section>
<section id="selectOption">
</section>
</li>
<li class="product_info_li">
<form id="product_add_form">
<ul class="product_order_ul">
<li class="product_order_li">
<input class="order_btn" type="button" value="찜하기">
</li>
<li class="product_order_li">
<input class="order_btn" type="button" value="장바구니에 담기" onclick="addCart()">
</li>
<li class="product_order_li">
<input class="order_btn" type="button" value="바로 주문하기">
</li>
</ul>
</form>
</li>
</ul>
</div>
</div>
<div class="product_info_menu">
<ul class="product_info_menu_ul">
<li class="product_info_menu_li">
<a id="proDetail_btn" onclick=' moveToProductInfoMenu()'>상세 정보</a>
</li>
<li class="product_info_menu_li">
<a id="proReview_btn">리뷰</a>
</li>
<li class="product_info_menu_li">
<a id="proQna_btn">문의</a>
</li>
</ul>
</div>
<div class="product_detail">
<div class="product_detailImage">
<c:forEach var="im" items="${ product.detailImage }">
<img class="detailImage" src="${ product.imageDir }${ im }"><br>
</c:forEach>
</div>
<div class="product_content">
${ product.proContent }
</div>
</div>
</div>
</div>
<%@ include file="/WEB-INF/views/client/base/client_footer.jspf" %>
</div>
</body>
</html>
|
2. client_productInfo.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
|
// 옵션 수량 변경
function count(num, name) {
var cnt = parseInt($("div[name='" + name + "'] input[name='cnt" + name + "']").val());
var odTotal = parseInt($("input[name='odTotal']").val());
let proPrice = parseInt($("input[name='proPrice']").val());
if (num == 1) {
odTotal += proPrice;
cnt++;
} else if (num == 2){
odTotal -= proPrice;
cnt--;
}
if (cnt < 1) {
cnt = 0;
$("div[name='" + name + "']").remove();
}
$("div[name='" + name + "'] input[name='cnt" + name + "']").val(cnt);
$("input[name='odTotal']").val(odTotal);
}
// 옵션 선택
function select(selectElement) {
var color = document.getElementById("opColor").value;
//console.log(color);
var size = document.getElementById("opSize").value;
//console.log(size);
var odTotal = parseInt($("input[name='odTotal']").val());
var proName = $("input[name='proName']").val();
var proId = $("input[name='proId']").val();
if(color === "SELECT" || size === "SELECT"){
return;
}
var name= color+size;
if($("#"+name).length){
alert("이미 선택한 옵션입니다.");
count(1, name);
} else {
var select = "";
select += "<div name='" + color + size + "' id='" + color + size + "' class='selectValue'>"
+ "<span class='proName'>" + proName + "</span> / " + color + " / " + size + " <br>"
+ "<button type='button' class='pro_btn' onclick='count(2,\"" + name +"\")'>-</button>"
+ "<input class='pro_btn' name='cnt" + name + "' style='width:35px; height:27px; margin-left:3px; margin-right:3px; text-align:center;' value=1>"
+ "<button type='button' class='pro_btn' onclick='count(1,\"" + name +"\")'>+</button>"
+ "<input type='hidden' name='opId' value='" + proId + name + "'>"
+ "<button id='id' name='" + name + "' class='pro_btn' onclick='deleteSelected(this)' style='flozat:right; margin-left:10px;'>X</button>"
+ "</div><br>";
count(1, name);
$("#selectOption").append(select);
}
// 초기화
document.getElementById("opColor").value = "SELECT";
document.getElementById("opSize").value = "SELECT";
}
function moveToProductInfoMenu(){
document.querySelector('.product_info_menu').scrollIntoView();
}
function deleteSelected(element){
let cnt = $(element).parent().find("input[name='cnt" + element.name + "']").val();
for(let i=0; i<cnt; i++){
count(2, element.name);
}
$(element).parent().remove();
}
// 장바구니에 추가
function addCart(){
let list = addList();
let proId = $("input[name='proId']").val();
list.forEach(product => {
console.log("opId : " + product.get("opId"));
console.log("caCnt : " + product.get("caCnt"));
$.ajax({
url: "/w2/clientAddCart.do?proId=" + proId,
type: "POST",
async: true,
dataType: "text",
data: JSON.stringify({
opId : product.get("opId"),
caCnt : product.get("caCnt")
}),
contentType: "application/json",
success: function(result){
if(result == 1) {
location.href="clientCart.do";
} else {
alert("일시적인 오류가 발생했습니다. 다시 시도해주세요");
}
},
error : function(error){
alert("ajax 실패");
}
});
});
}
// 상품 리스트에 담기
function addList(){
let list = [];
let productCounts = document.querySelectorAll(".selectValue");
productCounts.forEach(product => {
let colorSize = product.id;
let productMap = new Map();
productMap.set("opId", product.querySelector("input[name='opId']").value);
productMap.set("caCnt", product.querySelector("input[name='cnt" + colorSize + "']").value);
list.push(productMap);
});
return list;
}
|
>>> 쿠키 아이디를 랜덤으로 생성해야한다. 기존 프로젝트에서는 랜덤으로 생성하는 문자열이 많았는데 개별로 랜덤하게
생성했었는데 이를 공통 모듈로 묶어 작업하기로 함
3. com.w2.util패키지에 RandomString.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
|
package com.w2.util;
public class RandomString {
// 랜덤 문자열 생성
public static String setRandomString(int num) {
String spell = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
spell += "abcdefghijklmnopqrstuvwxyz";
spell += "1234567890";
StringBuilder builder;
builder = new StringBuilder(num);
for(int i=0; i<num; i++) {
int index = (int)(spell.length() * Math.random());
builder.append(spell.charAt(index));
}
return builder.toString();
}
}
|
4. ClientCartController.java 수정
/** 장바구니에 상품 추가 */
@PostMapping("clientAddCart.do")
public void clientAddCart(@RequestParam(value = "proId", required = true)String proId, @RequestBody Map<String, String> data, HttpSession session, ClientCartVO cartvo, HttpServletRequest request, HttpServletResponse response) throws IOException {
System.out.println("1. [ Client Cart Controller ] clientAddCart");
// 비로그인 상태인 경우
if(session.getAttribute("session") == null) {
Cookie cookie = WebUtils.getCookie(request, "cartCookie");
String ckId = null;
if(cookie == null) { // 쿠키가 생성된 적 없는 경우
ckId = RandomString.setRandomString(15);
Cookie newCookie = new Cookie("cartCookie", ckId);
newCookie.setComment("비회원 아이디");
newCookie.setPath("/w2/");
newCookie.setMaxAge(60*60*24*2);
response.addCookie(newCookie);
} else { // 이미 생성된 쿠키가 있는 경우
ckId = cookie.getValue();
// 쿠키 세션 재설정
cookie.setMaxAge(60*60*24*2);
response.addCookie(cookie);
}
cartvo.setCkId(ckId);
} else { // 로그인 상태인 경우
cartvo.setClientId((String)session.getAttribute("session"));
}
cartvo.setProId(proId);
cartvo.setOpId((String)data.get("opId"));
cartvo.setCaCnt(Integer.parseInt(data.get("caCnt")));
int result = cartService.clientAddCart(cartvo);
response.setContentType("application/json");
response.getWriter().write(String.valueOf(result));
}
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
|
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("clientAddCart.do")
public void clientAddCart(@RequestParam(value = "proId", required = true)String proId, @RequestBody Map<String, String> data, HttpSession session, ClientCartVO cartvo, HttpServletRequest request, HttpServletResponse response) throws IOException {
System.out.println("1. [ Client Cart Controller ] clientAddCart");
// 비로그인 상태인 경우
if(session.getAttribute("session") == null) {
Cookie cookie = WebUtils.getCookie(request, "cartCookie");
String ckId = null;
if(cookie == null) { // 쿠키가 생성된 적 없는 경우
ckId = RandomString.setRandomString(15);
Cookie newCookie = new Cookie("cartCookie", ckId);
newCookie.setComment("비회원 아이디");
newCookie.setPath("/w2/");
newCookie.setMaxAge(60*60*24*2);
response.addCookie(newCookie);
} else { // 이미 생성된 쿠키가 있는 경우
ckId = cookie.getValue();
// 쿠키 세션 재설정
cookie.setMaxAge(60*60*24*2);
response.addCookie(cookie);
}
cartvo.setCkId(ckId);
} else { // 로그인 상태인 경우
cartvo.setClientId((String)session.getAttribute("session"));
}
cartvo.setProId(proId);
cartvo.setOpId((String)data.get("opId"));
cartvo.setCaCnt(Integer.parseInt(data.get("caCnt")));
int result = cartService.clientAddCart(cartvo);
response.setContentType("application/json");
response.getWriter().write(String.valueOf(result));
}
/** 장바구니 상품 삭제 */
@PostMapping("clientDeleteCart.do")
public void clientDeleteCart(@RequestBody Map<String, String> 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 수정
// 장바구니에 상품 추가
int clientAddCart(ClientCartVO cartvo);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
package com.w2.client.cart;
import java.util.List;
public interface ClientCartService {
// 장바구니에 상품 추가
int clientAddCart(ClientCartVO cartvo);
// 장바구니 목록 불러오기
List<ClientCartVO> getClientCartList(ClientCartVO cartvo);
// 장바구니 상품 삭제
int clientDeleteCart(String string);
}
|
cs |
6. ClientCartServiceImpl.java 수정
// 장바구니에 상품 추가
@Override
public int clientAddCart(ClientCartVO cartvo) {
System.out.println("2. [ ClientCartService ] clientAddCart");
return cartDAO.clientAddCart(cartvo);
}
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
|
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 int clientAddCart(ClientCartVO cartvo) {
System.out.println("2. [ ClientCartService ] clientAddCart");
return cartDAO.clientAddCart(cartvo);
}
// 장바구니 목록 불러오기
@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. ClientCartDAO.java 수정
// 장바구니에 상품 추가
public int clientAddCart(ClientCartVO cartvo) {
System.out.println("3. [ CartDAO ] clientAddCart");
int check = sqlSessionTemplate.selectOne("CartDAO.clientCheckCart", cartvo);
// 이미 장바구니에 있는 상품인 경우
if (check == 1) {
// 같은 쿠키값 가진 상품 만료시간 업데이트
if(cartvo.getCkId() != null) {
System.out.println(">> 다른 상품 만료시간 업데이트");
sqlSessionTemplate.update("CartDAO.clientUpdateCookie", cartvo);
}
System.out.println(">> 상품 수량 변경");
return sqlSessionTemplate.update("CartDAO.clientUpdateCart", cartvo);
}
System.out.println(">> 상품 추가");
return sqlSessionTemplate.insert("CartDAO.clientAddCart", cartvo);
}
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
|
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 int clientAddCart(ClientCartVO cartvo) {
System.out.println("3. [ CartDAO ] clientAddCart");
int check = sqlSessionTemplate.selectOne("CartDAO.clientCheckCart", cartvo);
// 이미 장바구니에 있는 상품인 경우
if (check == 1) {
// 같은 쿠키값 가진 상품 만료시간 업데이트
if(cartvo.getCkId() != null) {
System.out.println(">> 다른 상품 만료시간 업데이트");
sqlSessionTemplate.update("CartDAO.clientUpdateCookie", cartvo);
}
System.out.println(">> 상품 수량 변경");
return sqlSessionTemplate.update("CartDAO.clientUpdateCart", cartvo);
}
System.out.println(">> 상품 추가");
return sqlSessionTemplate.insert("CartDAO.clientAddCart", cartvo);
}
// 장바구니 목록 불러오기
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);
}
}
|
8. client-cart-mapping.xml 수정
<!-- 장바구니에 상품 추가 -->
<insert id="clientAddCart" parameterType="clientCart">
INSERT INTO cart (proId, opId, caCnt,
<if test="clientId != null">
cId
</if>
<if test="clientId == null">
ckId
</if>
) VALUES ( #{ proId }, #{ opId }, #{ caCnt },
<if test="clientId != null">
#{ clientId }
</if>
<if test="clientId == null">
#{ ckId }
</if>
)
</insert>
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
|
<?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>
<!-- 장바구니 중복 상품 확인 -->
<select id="clientCheckCart" parameterType="clientCart" resultType="int">
SELECT COUNT(*) FROM cart
<where>
<if test="clientId != null">
cId = #{ clientId }
</if>
<if test="clientId == null">
ckId = #{ ckId }
</if>
AND proId = #{ proId } AND opId = #{ opId }
</where>
</select>
<!-- 장바구니에 상품 추가 -->
<insert id="clientAddCart" parameterType="clientCart">
INSERT INTO cart (proId, opId, caCnt,
<if test="clientId != null">
cId
</if>
<if test="clientId == null">
ckId
</if>
) VALUES ( #{ proId }, #{ opId }, #{ caCnt },
<if test="clientId != null">
#{ clientId }
</if>
<if test="clientId == null">
#{ ckId }
</if>
)
</insert>
<!-- 장바구니에 상품 수량 수정 -->
<update id="clientUpdateCart" parameterType="clientCart">
UPDATE cart SET caCnt=(caCnt + #{ caCnt })
<where>
proId = #{ proId } AND opId = #{ opId }
<if test="clientId != null">
AND cId = #{ clientId }
</if>
<if test="clientId == null">
AND ckId = #{ ckId }
</if>
</where>
</update>
<!-- 같은 쿠키 값 가진 장바구니 만료시간 수정 -->
<update id="clientUpdateCookie" parameterType="clientCart">
UPDATE cart SET ckLimit = (CURRENT_TIMESTAMP + INTERVAL 2 DAY)
WHERE ckId = #{ ckId }
</update>
<!-- 장바구니 상품 삭제 -->
<delete id="clientDeleteCart" parameterType="String">
DELETE FROM cart WHERE caId=#{ caId }
</delete>
</mapper>
|
reProject_14_장바구니 기능 구현_3_기능 실행 결과
reProject_13_장바구니 기능 구현_2_상품 상세 페이지에서 장바구니에 추가 기능 구현 2023.12.29 - [Project] - reProject_12_장바구니 기능 구현_1_장바구니 페이지 수정, 상품 선택 삭제, 전체 삭제 2023.12.28 --
hyeonga493.tistory.com
'Project_WEATHERWEAR' 카테고리의 다른 글
reProject_15_주문 페이지, 주문 상세 페이지 작업 (0) | 2024.01.03 |
---|---|
reProject_14_장바구니 기능 구현_3_기능 실행 결과 (0) | 2023.12.29 |
reProject_12_장바구니 기능 구현_1_장바구니 페이지 수정, 상품 선택 삭제, 전체 삭제 (1) | 2023.12.29 |
reProject_11_장바구니 페이지 구현 (1) | 2023.12.28 |
reProject_00_작업 일지 (0) | 2023.12.27 |