수업(국비지원)/Spring

[Spring] (MVC 2) 장바구니 생성(cart, CartController, ItemSet) - session사용, 장바구니 상품 추가(CartController, Cart)

byeolsub 2023. 4. 20. 23:57
  • 장바구니 생성

📌 CartController.java 생성

package controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import logic.Cart;
import logic.Item;
import logic.ItemSet;
import logic.ShopService;

@Controller
@RequestMapping("cart")
public class CartController {
	@Autowired
	private ShopService service;
	//http://localhost:8088/springmvc1/cart/cartAdd?id=1&quantity=1
	@RequestMapping("cartAdd")
	public ModelAndView add(Integer id, Integer quantity, HttpSession session) {
		ModelAndView mav = new ModelAndView("cart/cart"); //뷰 이름
		Item item = service.getItem(id); //상품 정보를 db에서 읽어 오기
		//session의 "CART" 속성에 장바구니 정보를 저장.
		Cart cart = (Cart)session.getAttribute("CART");
		if(cart == null) {
			cart = new Cart();
			session.setAttribute("CART", cart); //CART 객체를 속성에 등록
		}
		//cart의 itemSetList에 추가
		cart.push(new ItemSet(item, quantity));
		mav.addObject("cart",cart);
		mav.addObject("message", item.getName() + ":" + quantity + "개 장바구니 추가");
		return mav;
	}
}

 

 

📌 ItemSet.java 생성

package logic;

public class ItemSet {
	private Item item;
	private Integer quantity;
	
public ItemSet(Item item, Integer quantity) {
		this.item = item;
		this.quantity = quantity;
	}

//getter, setter, toString
	public Item getItem() {
		return item;
	}
	public void setItem(Item item) {
		this.item = item;
	}
	public Integer getQuantity() {
		return quantity;
	}
	public void setQuantity(Integer quantity) {
		this.quantity = quantity;
	}
	
	@Override
	public String toString() {
		return "ItemSet [item=" + item + ", quantity=" + quantity + "]";
	}	
}

 

 

📌 Cart.java 생성

package logic;

import java.util.ArrayList;
import java.util.List;

public class Cart {
	private List<ItemSet> itemSetList = new ArrayList<>();
	
	public List<ItemSet> getItemSetList() {
		return itemSetList;
	}
	public void push(ItemSet itemSet) {
		itemSetList.add(itemSet); //목록에 추가
	}
	public int getTotal() { //total get 프로퍼티
		int sum = 0;
		for(ItemSet is : itemSetList) {
			sum += is.getItem().getPrice() * is.getQuantity();
		}
		return sum;
	}
}

 

 

📌 cart.jsp 생성

<%@ 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" %>     
<%-- /springmvc1/src/main/webapp/WEB-INF/view/cart/cart.jsp --%>    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>장바구니</title>
</head>
<body>
<h2>장바구니</h2>
<table>
<tr><td colspan="4">장바구니 상품목록</td></tr>
<tr><th>상품명</th><th>가격</th><th>수량</th><th>합계</th></tr>
<c:forEach items="${cart.itemSetList}" var="set" varStatus="stat">
<tr><td>${set.item.name}</td>
    <td><fmt:formatNumber value="${set.item.price}" pattern="###,###"/></td>
    <td><fmt:formatNumber value="${set.quantity}" pattern="###,###"/></td>
    <td><fmt:formatNumber value="${set.quantity * set.item.price}" pattern="###,###"/>
    <a href="cartDelete?index=${stat.index}">ⓧ</a></td></tr>
</c:forEach>
<tr><td colspan="4" align="right">총 구입 금액 : 
<fmt:formatNumber value="${cart.total}" pattern="###,###"/>원</td></tr>
</table>
<br>
${message}
<br>
<a href="../item/list">상품목록</a>
<a href="checkout">주문하기</a>
</body>
</html>

  • 장바구니 상품 추가

📌 CartController.java 내용 추가

package controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import logic.Cart;
import logic.Item;
import logic.ItemSet;
import logic.ShopService;

@Controller
@RequestMapping("cart")
public class CartController {
	@Autowired
	private ShopService service;
	//http://localhost:8088/springmvc1/cart/cartAdd?id=1&quantity=1
	@RequestMapping("cartAdd")
	public ModelAndView add(Integer id, Integer quantity, HttpSession session) {
		ModelAndView mav = new ModelAndView("cart/cart"); //뷰 이름
		Item item = service.getItem(id); //상품 정보를 db에서 읽어 오기
		//session의 "CART" 속성에 장바구니 정보를 저장.
		Cart cart = (Cart)session.getAttribute("CART");
		if(cart == null) {
			cart = new Cart();
			session.setAttribute("CART", cart); //CART 객체를 속성에 등록
		}
		//cart의 itemSetList에 추가
		**//itemSetList 존재하는 상품이 추가 되는 경우 수량만 증가시킴**
		cart.push(new ItemSet(item, quantity));
		mav.addObject("cart",cart);
		mav.addObject("message", item.getName() + ":" + quantity + "개 장바구니 추가");
		return mav;
	}
}

 

 

📌 Cart.java 내용 추가

package logic;

import java.util.ArrayList;
import java.util.List;

public class Cart {
	private List<ItemSet> itemSetList = new ArrayList<>();
	
	public List<ItemSet> getItemSetList() {
		return itemSetList;
	}
	public void push(ItemSet itemSet) {
    **//itemSet : 추가 될 상품**
		**for(ItemSet is : itemSetList) {
      //is : 이미 추가 된 상품
			if(itemSet.getItem().getId() == is.getItem().getId()) {
				is.setQuantity(is.getQuantity() + itemSet.getQuantity());
				return;
			}**
		}
		itemSetList.add(itemSet); //목록에 추가
	}
	public int getTotal() { //total get 프로퍼티
		int sum = 0;
		for(ItemSet is : itemSetList) {
			sum += is.getItem().getPrice() * is.getQuantity();
		}
		return sum;
	}
}