hyeonga_code

reProject_36_사용자 장바구니 기능 구현(수량 변경, 선택 삭제, 전체 삭제) 본문

Project_WEATHERWEAR

reProject_36_사용자 장바구니 기능 구현(수량 변경, 선택 삭제, 전체 삭제)

hyeonga 2024. 1. 29. 05:59
반응형

 

reProject_35_사용자 메인페이지, 상품 목록 페이지 기능 구현

reProject_34_트랜잭션 적용하기 reProject_33_ZenBlog 부트스트랩을 사용하여 사용자 화면 작업(메인페이지, 상품 목록 페이지, 상품 reProject_32_배송관리 페이지 작업 2024.01.20 배송관리는 택배사를 관리

hyeonga493.tistory.com

2024.01.28

장바구니 페이지를 작업하려고 보니 ZenBlog에는 table 태그에 관련된 코드가 없어 기존에 작업한 화면을 적용하여 작업했다. 기능 부분도 기존의 작업을 적용하여 작업. 현재 회원/비회원 쪽 작업은 다른 팀원이 작업하는 중으로 session이 필요한 부분은 코드로 박아두고 작업했다. 추후 프로젝트를 합친 후에 다시 손봐야할 부분이다.

 

CartController.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
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
package com.w2.client.controller;
 
import java.io.IOException;
import java.util.List;
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.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.util.WebUtils;
 
import com.w2.cart.CartVO;
import com.w2.cart.service.CartService;
import com.w2.util.ClientCookie;
 
@Controller
public class CartController {
 
    @Autowired
    private CartService cartService;
    
    /**
     * 장바구니 화면 호출
     * @return
     */
    @RequestMapping("cart.do")
    public String cart(HttpServletRequest request, HttpSession session, Model model, CartVO cartvo) {
        /** 테스트 시작*/
        session.setAttribute("session""leee");
        /** 테스트 끝 */
        
        if((String)session.getAttribute("session"== null) {
            Cookie cookie = WebUtils.getCookie(request, "clientCookie");
            if (cookie != null) {
                cartvo.setCookieId((String)cookie.getValue());
            }
        } else {
            cartvo.setClientId((String)session.getAttribute("session"));
        }
        
        model.addAttribute("cartList", cartService.getCartList(cartvo));
        return "cart";
    }
    
    /** 장바구니에 상품 추가 */
    @PostMapping("cartInsert.do")
    public void cartInsert(@RequestBody List<CartVO> productList, HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException {
        /** 테스트 시작 */
        session.setAttribute("session""leee");
        /** 테스트 끝 */
        
        // 비로그인 상태인 경우
        if(session.getAttribute("session"== null) {
            String ckId = ClientCookie.setCookie(request, response);
            productList.get(0).setCookieId(ckId);
        } else { // 로그인 상태인 경우
            productList.get(0).setClientId((String)session.getAttribute("session"));
        }
        
        int result = cartService.insertCart(productList);
 
        response.setContentType("application/json");
        response.getWriter().write(String.valueOf(result));
    }
    
    /** 장바구니 수량 변경 */
    @PostMapping("cartUpdate.do")
    public void cartUpdate(@RequestBody Map<StringString> data, HttpSession session, CartVO cartvo, HttpServletRequest request, HttpServletResponse response) throws IOException {
        
        setUser(session, request, response, cartvo);
        cartvo.setCartId((String)data.get("cartId"));
        cartvo.setCartCnt(Integer.parseInt(data.get("cnt")));
        
        int result = cartService.updateCart(cartvo);
 
        setResponse(response, result, "application/json");
    }
    
    /** 장바구니 상품 삭제 */
    @PostMapping("cartDelete.do")
    public void cartDelete(@RequestBody Map<StringString> data, HttpSession session, CartVO cartvo, HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("1. [ Client Cart Controller ] clientAddCart");
        
        setUser(session, request, response, cartvo);
        
        int result = cartService.deleteCart((String)data.get("cartId"));
 
        setResponse(response, result, "application/json");
    }
    
    // 사용자 확인(회원/비회원)
    public CartVO setUser(HttpSession session, HttpServletRequest request, HttpServletResponse response, CartVO cartvo) {
        // 비로그인 상태인 경우
        if(session.getAttribute("session"== null) {
            String ckId = ClientCookie.setCookie(request, response);
            
            cartvo.setCookieId(ckId);
        } else { // 로그인 상태인 경우
            cartvo.setClientId((String)session.getAttribute("session"));
        }
        return cartvo;
    }
    
    // ajax 응답
    public HttpServletResponse setResponse(HttpServletResponse response, Object result, String type) throws IOException {
        response.setContentType(type);
        response.getWriter().write(String.valueOf(result));
        
        return response;
    }
}
 

 

 

CartVO.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.cart;
 
import java.util.Date;
 
import com.w2.product.OptionVO;
import com.w2.product.ProductVO;
 
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
 
@Setter
@Getter
@ToString
public class CartVO {
    private String cartId;       // 장바구니 번호
    private String productId;    // 상품 번호
    private String optionId;     // 옵션 번호
    private String clientId;     // 회원 번호
    private Date cartDate;       // 장바구니 추가 일자
    private int cartCnt;         // 수량
    private String cookieId;     // 쿠키 번호
    private String cookieLimit;  // 쿠키 만료 일자
 
    // join용
    private ProductVO product;   // 상품 정보, 이미지, 상품 가격
    private OptionVO option;     // 옵션 정보
}
 

 

 

CartService.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.w2.cart.service;
 
import java.util.List;
 
import com.w2.cart.CartVO;
 
public interface CartService {
 
    List<CartVO> getCartList(CartVO cartvo);    // 장바구니 목록 불러오기
    int updateCart(CartVO cartvo);              // 장바구니 수량 변경
    int deleteCart(String cartId);              // 장바구니 삭제
    int insertCart(List<CartVO> productList);   // 장바구니 추가
}
 

 

 

CartServiceImpl.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
package com.w2.cart.service;
 
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import com.w2.cart.CartDAO;
import com.w2.cart.CartVO;
 
@Service
public class CartServiceImpl implements CartService {
 
    @Autowired
    private CartDAO cartDAO;
    
    @Override
    public List<CartVO> getCartList(CartVO cartvo) {
        return cartDAO.getCartList(cartvo);
    }
 
    @Override
    public int updateCart(CartVO cartvo) {
        return cartDAO.updateCart(cartvo);
    }
 
    @Override
    public int deleteCart(String cartId) {
        return cartDAO.deleteCart(cartId);
    }
 
    @Override
    public int insertCart(List<CartVO> productList) {
        return cartDAO.insertCart(productList);
    }
}
 

 

 

CartDAO.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.w2.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 CartDAO {
 
    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;
    
    public List<CartVO> getCartList(CartVO cartvo) {
        return sqlSessionTemplate.selectList("CartDAO.getCartList", cartvo);
    }
 
    public int updateCart(CartVO cartvo) {
        return sqlSessionTemplate.update("CartDAO.updateCart", cartvo);
    }
 
    public int deleteCart(String cartId) {
        return sqlSessionTemplate.delete("CartDAO.deleteCart", cartId);
    }
 
    public int insertCart(List<CartVO> productList) {
        String ckId = null;
        String clientId = null;
        
        for(int i=0; i<productList.size(); i++) {
            // 회원/비회원 구분
            if(productList.get(0).getClientId() != null) {
                clientId = productList.get(0).getClientId();
            } else if(productList.get(0).getCookieId() != null) {
                ckId = productList.get(0).getCookieId();
            }
            
            CartVO cartvo = (CartVO)productList.get(i);
            
            if(i>0) {
                if(clientId != null) {
                    productList.get(i).setClientId(clientId);
                } else if (ckId != null) {
                    productList.get(i).setCookieId(ckId);
                }    
            }
            
            CartVO checkCart = sqlSessionTemplate.selectOne("CartDAO.checkCart", cartvo);
 
            // 이미 장바구니에 있는 상품인 경우
            if (checkCart != null) {
                // 같은 쿠키값 가진 상품 만료시간 업데이트
                if(cartvo.getCookieId() != null) {
                    System.out.println(">> 다른 상품 만료시간 업데이트");
                    sqlSessionTemplate.update("CartDAO.updateCookie", cartvo);
                }
                
                cartvo.setCartId(checkCart.getCartId());
                cartvo.setCartCnt(checkCart.getCartCnt()+cartvo.getCartCnt());
                
                System.out.println(">> 상품 수량 변경 > 입력 수량 : " + cartvo.getCartCnt());
                sqlSessionTemplate.update("CartDAO.updateCart", cartvo);
            }else {
                System.out.println(">> 상품 추가");
                sqlSessionTemplate.insert("CartDAO.insertCart", cartvo);
            }
        }
        return 1;
    }
 
}
 

 

 

cart-mapping.xml

-- 기존에 작업할 때에는 <collection> 태그를 사용하여 작업했었는데 <association>태그를 사용하여 필요한 데이터만 추출해서 작업했다. 

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
<?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="CartDAO">
    <resultMap type="com.w2.cart.CartVO" id="cart">
        <id property="cartId" column="cartId" />
        <result property="productId" column="productId" />
        <result property="clientId" column="clientId" />
        <result property="optionId" column="optionId" />
        <result property="cartDate" column="cartDate" />
        <result property="cartCnt" column="cartCnt" />
        <result property="cookieId" column="cookieId" />
        <result property="cookieLimit" column="cookieLimit" />
        
        <association property="product" javaType="product">
            <result property="productName" column="productName" />
            <result property="productPrice" column="productPrice" />
            <result property="mainImage" column="mainImage" />
        </association>
        
        <association property="option" javaType="option">
            <result property="optionColor" column="optionColor" />
            <result property="optionSize" column="optionSize" />
            <result property="stockCnt" column="stockCnt" />
        </association>
    </resultMap>
    
    <sql id="checkClient">
        <if test="clientId != null">clientId</if>
        <if test="clientId == null">cookieId</if>
    </sql>
    
    <sql id="setClient">
        <if test="clientId != null">clientId = #{ clientId }</if>
        <if test="clientId == null">cookieId = #{ cookieId }</if>
    </sql>
    <!-- 장바구니 목록 조회 -->
    <select id="getCartList" parameterType="cart" resultMap="cart">
        SELECT pro.productId, pro.productName, ca.optionId,
                CONCAT(pm.imageDir, pm.imageName) as mainImage,
                op.optionColor, op.optionSize, pri.productPrice, 
                ca.cartCnt, ca.cartId,
                <include refid="checkClient"/>
        FROM cart ca
        LEFT JOIN product pro ON ca.productId = pro.productId
        LEFT JOIN product_image pm ON ca.productId = pm.imageBy AND pm.imageStatus='대표'
        LEFT JOIN option_info op ON ca.optionId = op.optionId
        LEFT JOIN product_price pri ON ca.productId = pri.productId
        <where>
            <include refid="setClient"/>
        </where>
    </select>
    
<!-- 장바구니 중복 상품 확인 -->
    <select id="checkCart" parameterType="cart" resultType="cart">
        SELECT * FROM cart
        <where>
            <include refid="setClient"/>
            AND proId = #{ productId } AND opId = #{ optionId }
        </where>
    </select>
 
<!-- 장바구니에 상품 추가 -->
    <insert id="insertCart" parameterType="cart">
        INSERT INTO cart (productId, optionId, cartCnt, 
            <include refid="checkClient"/>
        ) VALUES ( #{ productId }, #{ optionId }, #{ cartCnt },
            <include refid="checkClient"/>
        )
    </insert>
    
<!-- 장바구니에 상품 수량 수정 -->
    <update id="updateCart" parameterType="cart">
        UPDATE cart SET cartCnt=#{ cartCnt }
        <where>
            <include refid="setClient"/>
            AND cartId = #{ cartId }
        </where>
    </update>
 
<!-- 장바구니 상품 삭제 -->
    <delete id="deleteCart" parameterType="String">
        DELETE FROM cart WHERE cartId=#{ cartId }
    </delete>    
    
<!-- 같은 쿠키 값 가진 장바구니 만료시간 수정 -->
    <update id="updateCookie" parameterType="cart">
        UPDATE cart SET cookieLimit = (CURRENT_TIMESTAMP + INTERVAL 2 DAY)
        WHERE cookieId = #{ cookieId }
    </update>
    
<!-- 만료된 쿠키 정보 삭제 -->
    <delete id="checkCookieLimit">
        DELETE FROM cart 
        WHERE cookieLimit <![CDATA[< CURRENT_TIMESTAMP ]]>
    </delete>
    
</mapper>

 

 

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?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.admin.AdminVO" alias="admin"/>
    <typeAlias type="com.w2.client.ClientVO" alias="client"/>
    <typeAlias type="com.w2.board.NoticeVO" alias="notice"/>
    <typeAlias type="com.w2.board.QnaVO" alias="qna"/>
    <typeAlias type="com.w2.board.TermsVO" alias="terms"/>
    <typeAlias type="com.w2.product.ProductVO" alias="product"/>
    <typeAlias type="com.w2.product.ProductPriceVO" alias="productPrice"/>
    <typeAlias type="com.w2.product.OptionVO" alias="option"/>
    <typeAlias type="com.w2.order.OrderVO" alias="order"/>
    <typeAlias type="com.w2.delivery.DeliveryVO" alias="delivery"/>
    
    <typeAlias type="com.w2.cart.CartVO" alias="cart"/>
</typeAliases>
 
<!-- SQL 작성문을 지정하여 mapper 파일 경로 알려주는 역할입니다. -->
<mappers>
    <mapper resource="mappings/admin-mapping.xml"/>
    <mapper resource="mappings/notice-mapping.xml"/>
    <mapper resource="mappings/client-mapping.xml"/>
    <mapper resource="mappings/qna-mapping.xml"/>
    <mapper resource="mappings/terms-mapping.xml"/>
    <mapper resource="mappings/product-mapping.xml"/>
    <mapper resource="mappings/order-mapping.xml"/>
    <mapper resource="mappings/delivery-mapping.xml"/>
    
    <mapper resource="mappings/cart-mapping.xml"/>
</mappers>
</configuration>

 

cart.js > client_cart.js 수정

 

 

>> 실행

-- 선택한 상품이 없는 경우 전체 상품 가격을 표시

 

 

>> 상품 수량 변경시 DB에 업데이트

 

 

>> 상품 삭제

 

 

>> 선택 상품 있는 경우 선택한 상품 가격 표시

 

>> 전체 삭제

 

reProject_37_사용자 상품 상세 페이지 기능 구현 옵션 선택/삭제/수량 변경

2024.01.28 상품 상세 페이지 작업은 reProject 시 작업한 파일을 가져다가 수정해서 작업했다. 아래 파일은 관리자에서 사용한 코드를 동일하게 사용했다. - ProductService.java - ProductServiceImple.java - Produc

hyeonga493.tistory.com

 

반응형