πŸ’» JAVA_

[Servlet] μžλ°” μ„œλΈ”λ¦Ώμ„ ν™œμš©ν•œ μ‡Όν•‘ 카트 μƒν’ˆ μˆ˜λŸ‰ 쑰절 κΈ°λŠ₯ κ΅¬ν˜„ πŸš€

Joyfullyever 2025. 4. 7. 01:12

βœ… μ›Ήμ‚¬μ΄νŠΈμ˜ λ°˜μ‘μ„±

• μ‚¬μš©μž κ²½ν—˜μ„ κ·ΉλŒ€ν™”ν•˜λŠ” μš”μ†Œ 쀑 ν•˜λ‚˜

→ μ‚¬μš©μžκ°€ μƒν’ˆ μˆ˜λŸ‰μ„ λ³€κ²½ν•  λ•Œλ§ˆλ‹€ νŽ˜μ΄μ§€λ₯Ό μƒˆλ‘œκ³ μΉ¨ν•˜μ§€ μ•Šκ³ λ„ λ³€κ²½ 사항이 μ¦‰μ‹œ 반영

→ μ‚¬μš©μžλŠ” 더 λΉ λ₯΄κ³  μ›ν™œν•˜κ²Œ μ§„ν–‰

 

1️⃣ 기술 μŠ€νƒ

• μ£Όμš” κΈ°μˆ μ€ μžλ°” μ„œλΈ”λ¦Ώ

→ μžλ°” μ„œλΈ”λ¦Ώμ€ μ„œλ²„ μ‚¬μ΄λ“œμ—μ„œ μ‹€ν–‰λ˜λŠ” μžλ°” ν”„λ‘œκ·Έλž¨

→ ν΄λΌμ΄μ–ΈνŠΈμ˜ μš”μ²­μ„ μ²˜λ¦¬ν•˜κ³  응닡을 λŒλ €μ£ΌλŠ” μ—­ν• 

 

2️⃣ μš”μ²­ νŒŒλΌλ―Έν„° 처리

• cartProductNumber : μƒν’ˆμ˜ 고유 번호

• productCount : μ‘°μ •ν•˜κ³ μž ν•˜λŠ” μˆ˜λŸ‰

• cartProductCondition : μˆ˜λŸ‰ 쑰절 λ°©ν–₯ (upCartProductCount λ˜λŠ” downCartProductCount)

int cartProductNumber = Integer.parseInt(request.getParameter("cartProductNumber"));
int newProductCount = Integer.parseInt(request.getParameter("productCount"));
String cartProductCondition = request.getParameter("cartProductCondition");

 

 

3️⃣ μƒν’ˆ μˆ˜λŸ‰ 쑰절 둜직

• cartProductCondition에 따라 μƒν’ˆ μˆ˜λŸ‰μ„ μ¦κ°€μ‹œν‚€κ±°λ‚˜ κ°μ†Œμ‹œν‚€λŠ” λ‘œμ§μ„ μ‹€ν–‰

→ upCartProductCountλŠ” μˆ˜λŸ‰μ„ 증가

→ downCartProductCountλŠ” μˆ˜λŸ‰μ„ κ°μ†Œ

→ ν•΄λ‹Ή μƒν’ˆμ„ μ‡Όν•‘ μΉ΄νŠΈμ—μ„œ μ°Ύμ•„ μˆ˜λŸ‰μ„ μ‘°μ •, κ²°κ³Όλ₯Ό ν΄λΌμ΄μ–ΈνŠΈμ—κ²Œ μ¦‰μ‹œ 반영

if ("upCartProductCount".equals(cartProductCondition)) {
    // μˆ˜λŸ‰ 증가 둜직
    for (Map<String, Object> cartItem : shoppingCart) {
        if ((int) cartItem.get("productNumber") == cartProductNumber) {
            int currentCount = (int) cartItem.get("cartProductCount");
            cartItem.put("cartProductCount", currentCount + newProductCount);
            out.print("true");
            out.flush();
            break;
        }
    }
} else if ("downCartProductCount".equals(cartProductCondition)) {
    // μˆ˜λŸ‰ κ°μ†Œ 둜직
    for (Map<String, Object> cartItem : shoppingCart) {
        if ((int) cartItem.get("productNumber") == cartProductNumber) {
            int currentCount = (int) cartItem.get("cartProductCount");
            cartItem.put("cartProductCount", currentCount - newProductCount);
            out.print("true");
            out.flush();
            break;
        }
    }
}

 

4️⃣ μ‡Όν•‘ 카트 μ—…λ°μ΄νŠΈ 둜직

μ‚¬μš©μžμ˜ μš”μ²­μ„ 받은 ν›„, μ„œλΈ”λ¦Ώμ€ μ„Έμ…˜μ—μ„œ μ‡Όν•‘ 카트λ₯Ό μ°Ύκ³  μƒν’ˆ λ²ˆν˜Έκ°€ μ‘΄μž¬ν•˜λŠ”μ§€ 확인

→ λ§Œμ•½ μ‘΄μž¬ν•˜κ³  μˆ˜λŸ‰μ— 차이가 μžˆλ‹€λ©΄, μƒˆλ‘œμš΄ μˆ˜λŸ‰μœΌλ‘œ μ—…λ°μ΄νŠΈ

HashMap<Integer, Integer> cart = (HashMap<Integer, Integer>) session.getAttribute("shoppingCart");
if (cart.containsKey(cartProductNumber) && cart.get(cartProductNumber) != newProductCount) {
    cart.put(cartProductNumber, newProductCount);
}

 

5️⃣ κ²°κ³Ό 반영 및 μ‚¬μš©μž ν”Όλ“œλ°±

• λ³€κ²½λœ κ²°κ³ΌλŠ” μ¦‰μ‹œ μ‚¬μš©μžμ—κ²Œ 반영

• 좔가적인 νŽ˜μ΄μ§€ λ‘œλ”© 없이 이루어짐 → μ„œλΉ„μŠ€κ°€ λ”μš± λΉ λ₯΄κ³  λ°˜μ‘μ 