장바구니 만들기

조수경·2022년 1월 19일
0

JSP

목록 보기
35/45

장바구니는 세션으로 만들어짐
장바구니에 b가 있으면 수량을 증가시킴
없으면 b를 넣고 수량을 1로 처리해야함
장바구니를 비울 수 있으면 session.invalidatell;로 가능함

웹브라우저 하나당 하나의 세션

주문은 쿠키를 이용함

Product.java에 quantitiy(장바구니에 담은 개수) 추가

product.jsp

<%@page import="dto.Product"%>
<%@page import="ch04.com.dao.ProductRepository"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page errorPage="/exceptionNoProductId.jsp" %>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" 
href="<%=request.getContextPath()%>/css/bootstrap.min.css" />
<title>상품 상세 정보</title>
<script type="text/javascript">

상품주문 버튼을 클릭했을때 사용할 함수 만듬

confirm는 alert와 같은 기능을함

function addToCart(){
	//확인 : true , 취소 : false
	if(confirm("상품을 장바구니에 추가하시겠습니까?")){ //확인
		document.addForm.submit();
	}else{ //취소
		document.addForm.reset();
	}
	
}
</script>
</head>
<body>
<%-- <jsp:useBean id="productDAO" class="ch04.com.dao.ProductRepository" /> --%>
<%
	ProductRepository productDAO = ProductRepository.getInstance();
%>
	<div class="jumbotron">
		<div class="container">
			<h1 class="display-3">상품 정보</h1>
		</div>
	</div>
	<%
	//product.jsp?id=P1234
	String id = request.getParameter("id");
// 	out.print("id : " + id + "<br />");
	
// 	ProductRepository productDAO = new ProductRepository();
	Product product = productDAO.getProductById(id); //기본키를 가져오는것
	
	//null.toString() -> 오류 임의 발생(errorPage 발생 유도)
	product.toString();
	%>
	<!-- 자바세계를 jsp세계의 product로 만듬 -->
	<c:set var="product" value="<%=product%>" />
	<div class="container">
		<div class="row">
			<div class="col-md-5">
				<img src="/upload/${product.filename}" style="width:100%;" />
			</div>
			<div class="col-md-6">
				<h3>${product.pname}</h3>
				<p>${product.description}</p>
				<p>
					<b>상품코드 : </b>
					<span class="badge badge-danger">${product.productId}</span>
				</p>
				<p><b>제조사</b> : ${product.manufacturer}</p>
				<p><b>분류</b> : ${product.category}</p>
				<p><b>제고 수</b> : ${product.unitsInStock}</p>
				<h4>${product.uniPrice}원</h4>
				<p>
					<form name="addForm" method="post" 
					      action="addCart.jsp?id=${product.productId}"> <!-- 파람을 던지는 것(보내는것) -->
						<a href="#" class="btn btn-info" onclick="addToCart()">
						상품 주문 &raquo;</a>
						<a href="cart.jsp" class="btn btn-warning">장바구니 &raquo;</a>
						<a href="products.jsp" class="btn btn-secondary">상품 목록 &raquo;</a>
					</form>
				</p>
			</div>
		</div>
	</div>
</body>
</html>

cart.jsp

<%@page import="dto.Product"%>
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

장바구니는 세션으로 만들어져야 함

<%
	//세션의 고유 아이디를 가져옴
	String cartId = session.getId();
%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/css/bootstrap.min.css" />
<title>장바구니</title>
</head>
<body>
<!-- top.jsp 인클루드 시작 -->
	<jsp:include page="/ch03/top.jsp" />
<!-- top.jsp 인클루드 끝 -->
	<div class="jumbotron">
		<div class="container">
			<h1 class="display-3">장바구니</h1>
		</div>
	</div>
	<div class="container">
		<div class="row">
			<table width="100%">
				<tr>
					<td align="left">
						<a href="deleteCart.jsp?cartId=<%=cartId%>" 
						class="btn btn-danger">삭제하기</a>
					</td>
					<td align="right">
						<a href="shippingInfo.jsp?cartId=<%=cartId%>" 
						class="btn btn-success">주문하기</a>
					</td>
				</tr>
			</table>
		</div>

장바구니 목록 구현 시작

	<div style="padding-top:50px;">
		<table class="table table-hover">
			<tr>
				<th>상품</th>
				<th>가격</th>
				<th>수량</th>
				<th>소계</th>
				<th>비고</th>
			</tr>
      <%
      ArrayList<Product> cartList = (ArrayList<Product>)session.getAttribute("cartlist");
      // out.print("cartList 크기 : " + cartList);
      //cartList : 장바구니
      if(cartList == null){
          cartList = new ArrayList<Product>();
      }
      int sum = 0;	//total을 누적
      for(int i=0;i<cartList.size();i++){
          Product product = cartList.get(i);
          //금액 = 가격 * 수량  
          //새우깡 1500원 * 10봉지 => 15000원 소비
          int total = product.getUniPrice() * product.getQuantity();
          //total을 누적
          sum = sum + total;
      %>
		<tr>
			<td><%=product.getProductId()%>-<%=product.getPname()%></td>
			<td><%=product.getUniPrice()%></td>
			<td><%=product.getQuantity()%></td>
			<td><%=total%></td>
			<td>삭제</td>
		</tr>
<%
}
%>
		<tr>
			<th></th>
			<th></th>
			<th>총액</th>
			<th><%=sum%></th>
			<th></th>
		</tr>
			</table>
			<a href="products.jsp" class="btn btn-secondary">&raquo; 쇼핑 계속하기</a>
		</div>
		<!-- 장바구니 목록 구현 끝 -->
	</div>

<!-- bottom.jsp 인클루드 시작 -->
	<jsp:include page="/ch03/bottom.jsp" />
<!-- bottom.jsp 인클루드 끝 -->
</body>
</html>

</body>
</html>

addCart.jsp

<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@page import="dto.Product"%>
<%@page import="ch04.com.dao.ProductRepository"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

id가 없거나 값이 없을 때 돌려보내줌

<%

 String id = request.getParameter("id");

if(id==null || id.trim().equals("")){
	//문자열 좌우에서 공백을 제거하는 함수가 trim() 함수
	//돌려보내야함
	response.sendRedirect("products.jsp");
	return;
}

상품 저장소 객체를 생성해보자

(싱글톤: 하나의 메모리에서 전역 변수로 사용됨 = static)

ProductRepository dao = ProductRepository.getInstance();
//controller : 크롬에서 오는 모든 요청을 받아들이는것 
//service : 비즈니스 로직을 의미함
//dao : 상품과 관련되어있어서 dao를 사용하는것

해당 상품 아이디에 해당하는 정보를 얻어와보자

Product product = dao.getProductById(id); //기본키를 받아서 해당 상품을 가져온다
//이러면 멤머변수에 담기게 되는 것

id의 값이 P9999 이런 경우 상품이 없다

if(product == null){
	response.sendRedirect("/exceptionNoProductId.jsp");
}

모든 상품을 가져와보자

List<Product> goodsList = dao.getAllProducts();
//goodsList에서 하나를 끄집어내면 Product가 나옴
Product goods = new Product();
for(int i=0;i<goodsList.size();i++){
	//요청 파라미터 아이디의 상품이 존재하는지 검사
	//A.equals(id) 넘어온 아이디와 끄집어온 아이디값을 비교해야하는데 list가 어떻게 String이될까?
	goods = goodsList.get(i);	//product와 goods는 같다...?
	if(goods.getProductId().equals(id)){
		//for문에서 벗어나라
		break;
	}
}

*요청 파라미터 아이디의 상품을 담은 장바구니를 초기화

// 세션:cartlist를 얻어와 ArrayLsit 객체에 저장
ArrayList<Product> list = (ArrayList<Product>)session.getAttribute("cartlist");
out.print("list의 크기 : " + list);
// 만약 cartlist라는 세션 정보가 없다면 ArrayList객체를 생성하고 cartlist세션 생성
if(list == null){
	list = new ArrayList<Product>();
	session.setAttribute("cartlist", list);//장바구니
}

//list : 장바구니에 담긴 상품 목록
int cnt = 0;
Product goosQnt = new Product();
for(int i=0;i<list.size();i++){
	goosQnt = list.get(i);//list에서 끄집어내기
	//객체 = 리스트(객체들이 모인 것)
	//요청 파라미터 아이디 addCart.jsp?id=P1234의 상품이
	//장바구니에 담김 목록에 있다면
	//해당 상품의 수량을 1증가
	if(goosQnt.getProductId().equals(id)){
		cnt++;
		int orderQuantity = goosQnt.getQuantity() + 1;
		goosQnt.setQuantity(orderQuantity);
	}
}

//요청 파라미터 아이디addCart.jsp?id=P1234의 상품이
//장바구니에 담긴 목록에 없다면
//해당 상품의 수량을 1로 처리
if(cnt == 0){
	goods.setQuantity(1);
	list.add(goods);
}

response.sendRedirect("product.jsp?id="+id);

%>

deleteCart.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String id = request.getParameter("cartId");
if(id==null || id.trim().equals("")){
	response.sendRedirect("cart.jsp");
	return;
}
//장바구니에 등록된 모든 상품을 삭제하기 위함
session.invalidate();

//cart.jsp로 되돌아가기
response.sendRedirect("cart.jsp");

%>
profile
신입 개발자 입니다!!!

0개의 댓글