카테고리 없음

장바구니 만들기 | Cart 클래스 | 세션으로 저장

선이데이 2022. 5. 8. 05:49

장바구니는 DB저장안하고 세션으로 저장 

HttpSession session

 

세션

클라이언트 별로 서버에 저장되는 정보이다.
사용자 컴퓨터에 저장되던 쿠키와 다르게 서버에 저장되므로 비교적 보안이 필요한 데이터는 쿠키보다 세션에 저장한다.
서버가 종료되거나 유효시간이 지나면 사라진다.

 

 

세션 과정

웹 클라이언트가 서버에게 요청을 보내면 서버는 클라이언트를 식별하는 session id를 생성한다.
서버는 session id로 key와 value를 저장하는 HttpSession을 생성하고,
session id를 저장하고 있는 쿠키를 생성하여 클라이언트에게 전송한다.

클라이언트는 서버 측에 요청을 보낼 때, session id를 가지고 있는 쿠키를 전송한다.
서버는 쿠키의 session id로 HttpSession을 찾는다.

 

1. 세션 값 조회하기

getAttribute(String name) : 

 

 

2. 세션 값 저장하기

session.setAttribute(이름, 값)

 


장바구니에 추가 get매핑 add

 

- 세션에 제품 저장하기 (해쉬맵)

 

1. cart는 해쉬맵<id, 카트> 으로 장바구니를 만듬 
HashMap<Integer, Cart> cart = new HashMap<>(); 

 

2. 아이디와 카트객체들을 넣는다.
cart.put(id, new Cart(id, product.getName(), getPrice(),1,getImage()) 

 

3. 세션에 저장

session.setAttribute("cart", cart);

 

 

1. 처음 장바구니를 만들때 if

if(session.getAttribute("cart") == null) { //getAttribute : 세션값 조회 
    //1-1. 맵<id,카트> 로 리스트를 만든다.
    HashMap<Integer, Cart> cart = new HashMap<>();
    //1-2. id,카트객체들을 넣는다.
    cart.put(id, new Cart(id, product.getName(), product.getPrice(),1, product.getImage()));
    //1-3. 세션에 저장
    session.setAttribute("cart", cart);
  }

 

2. 이미 장바구니가 있을 경우  session.getAttribute("cart"); 

 - 2-1. 제품이 담긴경우

 - 2-2. 제품 없는경우

else {
    HashMap<Integer, Cart> cart = (HashMap<Integer, Cart>)session.getAttribute("cart"); 
}if(cart.containsKey(id)) {  //2-1 제품 있을경우
    int qty = cart.get(id).getQuantity(); //현재카트의 수량
    cart.put(id, new Cart(id, product.getName(), product.getPrice(),++qty, product.getImage())); //수량추가			
}else { //2-2. 제품 없는경우
    cart.put(id, new Cart(id, product.getName(), product.getPrice(),1, product.getImage()));
    session.setAttribute("cart", cart);
}

카트를 getAttribute 가져올때 object로 저장되기 때문에 해쉬맵으로 타입변환해서 가져오기

 

(경고가 뜨는데 그대로 해도 괜찮지만!) 

@SuppressWarnings("unchecked") 해준다 하지만

전체 적용을 위해 GetMapping 밑에다 넣어주기!!

else { 
    @SuppressWarnings("unchecked")
    HashMap<Integer, Cart> cart = (HashMap<Integer, Cart>)session.getAttribute("cart"); 
}

 

 

※ 헷갈릴 수 있는 것

예를들어 Cart 가 3개가 있다

(1, cart객체) 

(2, cart객체)

(3, cart객체)

 

 2-1. 제품이 담긴경우

    2번 카트의 수량을 불러와서 -> cart.get(2).getQuantity()

    수량을 업데이트 ++qty 

 2-2. 제품 없는경우

    없는 카트를 새로운 (4, cart객체) 에 만들어져서

    카트를 세션에 저장

if(cart.containsKey(id)) {  //2-1 제품 있을경우
    int qty = cart.get(id).getQuantity(); //현재카트의 수량
    cart.put(id, new Cart(id, product.getName(), product.getPrice(),++qty, product.getImage())); //수량추가			
}else { //2-2. 제품 없는경우
    cart.put(id, new Cart(id, product.getName(), product.getPrice(),1, product.getImage()));
    session.setAttribute("cart", cart);
}

 

모든 페이지에 장바구니 보여지도록

Common

 

// 현재 카트 상태 (없으면 false)
boolean cartActive = false; 

//카트가 있으면
if(session.getAttribute("cart") != null) {
    @SuppressWarnings("unchecked")
    HashMap<Integer, Cart> cart = (HashMap<Integer, Cart>)session.getAttribute("cart"); 

    int size = 0; //장바구니 상품 갯수
    int totalPrice = 0; //총 가격

    //장바구니 cart객체 반복 (1,cart객체) (2,cart객체)... id빼고 객체만
    for(Cart item : cart.values()) {
        size += item.getQuantity(); // 장바구니 갯수
        totalPrice += item.getQuantity() * Integer.parseInt(item.getPrice()); //가격 문자형인데 int형변환 해주기
    }
    model.addAttribute("size", size);
    model.addAttribute("totalPrice", totalPrice);

    cartActive = true;
}

model.addAttribute("cartActive", cartActive); //없으면 false 있으면 true

??

model.addAttribute("cartActive", cartActive); 

는 어떻게 보여질지 모르겠음..

 

 

☆주의

totalPrice += item.getQuantity() * Integer.parseInt(item.getPrice()); 

cart의 price는 String이고 totalPrice은 int 

형변환해주기!!

반응형
LIST