장바구니 만들기
기본이 세션, 쿠키가 양념
쿠키는 크롬에 저장을 하고, 세션은 톰켓에 저장한다
웹브라우저를 실행하면 JSessionID가 자동으로 생성되고, 쿠키에 들어간다.
장바구니는 세션, 장바구니 Id = 세션 Id
<%@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" %>
<%@ page import="dto.Product"%>
<%@ page import="ch04.com.dao.ProductRepository"%>
<%@ page import="java.util.List"%>
<%
String id = request.getParameter("id");
//id가 없거나 값이 없을 때
if(id==null||id.trim().equals("")){
response.sendRedirect("products.jsp");
return;
}
//상품저장소 객체 생성
ProductRepository dao = ProductRepository.getInstance();
//상품 아이디에 해당하는 정보를 얻어와보자
Product product = dao.getProductById(id);
//id의 값이 P999 이런 경우 상품이 없다
if(product == null){
response.sendRedirect("/exceptionNoProductId.jsp");
}
//모든 상품을 가져와보자
List<Product> goodsList = dao.getAllProducts();
Product goods = new Product();
for(int i=0; i<goodsList.size();i++){
//요청 파라미터 아이디의 상품이 존재하는지 검사
goods = goodsList.get(i);
//A.equals(id)
if(goods.getProductId().equals(id)){
//for문에서 벗어나라
break;
}
}
//*요청 파라미터 아이디의 상품을 담은 장바구니를 초기화
//세션 : cartlist를 얻어와 Array 객체에 저장
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 goodsQnt = new Product();
for(int i=0; i<list.size();i++){
//요청 파라미터 아이디 addCart.jsp?id=P1234의 상품이 장바구니에 담긴 목록에 있다면
//해당 상품의 수량을 1 증가
goodsQnt = list.get(i);
if(goodsQnt.getProductId().equals(id)){
cnt++;
int orderQuantity = goodsQnt.getQuantity() + 1;
goodsQnt.setQuantity(orderQuantity);
}
}
//요청 파라미터 아이디 addCart.jsp?id=P1234의 상품이 장바구니에 담긴 목록에 없다면
//해당 상품의 수량을 1로 처리
if(cnt == 0){
goods.setQuantity(1);
list.add(goods);
}
response.sendRedirect("product.jsp?id=" + id);
%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="dto.Product"%>
<%@ page import="ch04.com.dao.ProductRepository"%>
<%@ page errorPage="/exceptionNoProductId.jsp" %>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/css/bootstrap.min.css" />
<title>상품 상세 정보</title>
<script type="text/javascript">
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 />");
//예전엔 이렇게 썼지만 이제는 useBean사용
// ProductRepository productDAO = new ProductRepository();
Product product = productDAO.getProductById(id);
//null.toString() -> 오류 임의 발생(errorPage 발생 유도)
product.toString();
%>
<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()">상품 주문»</a>
<a href="cart.jsp" class="btn btn-warning">장바구니»</a>
<a href="products.jsp" class="btn btn-secondary">상품목록»</a>
</form>
</p>
</div>
</div>
</div>
</body>
</html>
<%@ 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");
%>
<%@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 import="dto.Product"%>
<%@ page import="java.util.List"%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/css/bootstrap.min.css" />
<title>상품 목록</title>
</head>
<body>
<%-- <jsp:useBean id="productDAO" class="ch04.com.dao.ProductRepository" /> --%>
<%
ProductRepository productDAO = ProductRepository.getInstance();
%>
<!-- top.jsp 인클루드 시작 -->
<jsp:include page="/ch03/top.jsp" />
<!-- top.jsp 인클루드 끝 -->
<!-- jumbotron 스타일 시작 -->
<div class="jumbotron">
<div class="container">
<!-- container -> 이 안에 내용이 있을거야 -->
<h1 class="display-3">상품 목록</h1>
</div>
</div>
<!-- jumbotron 스타일 끝 -->
<%
List<Product> listOfProducts = productDAO.getAllProducts();
%>
<div class="container">
<div class="row" align="center">
<!-- row -> 행 단위로 찍을거야 -->
<!-- 상품 반복 시작 -->
<%
for(int i=0; i<listOfProducts.size(); i++){
Product product = listOfProducts.get(i);
%>
<div class="col-md-4">
<img src="/upload/<%=product.getFilename()%>" style="width: 350px; height: 300px"/>
<h3><%=product.getPname() %></h3>
<p><%=product.getDescription() %></p>
<p><%=product.getUniPrice() %>원</p>
<p><a href="product.jsp?id=<%=product.getProductId() %>" class="btn btn-secondary" role="button">상세 정보»</a></p>
</div>
<%
}//end for
%>
<!-- 상품 반복 끝 -->
</div>
</div>
<!-- bottom.jsp 인클루드 시작 -->
<jsp:include page="/ch03/bottom.jsp" />
<!-- bottom.jsp 인클루드 끝 -->
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/css/bootstrap.min.css" />
<title>배송 정보</title>
</head>
<body>
<!-- top 인클루드 시작 -->
<jsp:include page="/ch03/top.jsp" />
<!-- top 인클루드 끝 -->
<div class="jumbotron">
<div class="container">
<h1 class="display-3">배송 정보</h1>
</div>
</div>
<div class="container">
<form method="post" class="form-horizontal" action="shippinginfo_process.jsp">
<input type="hidden" name="cartId" value="${param.cartId}" />
<div class="form-group row">
<label class="col-sm-2">성명</label>
<div class="col-sm-3">
<input type="text" name="name" class="form-control" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2">배송일</label>
<div class="col-sm-3">
<input type="text" name="shippingDate" class="form-control" />
(yyyy/mm/dd)
</div>
</div>
<div class="form-group row">
<label class="col-sm-2">국가</label>
<div class="col-sm-3">
<input type="text" name="country" class="form-control" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2">우편번호</label>
<div class="col-sm-3">
<input type="text" name="zipCode" class="form-control" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2">주소</label>
<div class="col-sm-3">
<input type="text" name="addressName" class="form-control" />
</div>
</div>
<div class="form-group row">
<div class="col-sm-offset-2 col-sm-10">
<!-- ?cartId=3F33D163E0590415FB7AB78354FC6BD3 -->
<a href="shippingInfo.jsp?cardId=${param.cartId}" class="btn btn-secondary" role="button">이전</a>
<input type="submit" class="btn btn-primary" value="등록" />
<a href="checkOutcancelled.jsp" class="btn btn-secondary" role="button">취소</a>
</div>
</div>
</form>
</div>
<!-- bottom 인클루드 시작 -->
<jsp:include page="/ch03/bottom.jsp" />
<!-- bottom 인클루드 끝 -->
</body>
</html>
<%@page import="java.net.URLEncoder"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
request.setCharacterEncoding("UTF-8");
//쿠키 생성 문법?
//Cookie 객체명 = new Cookie(name,value);
Cookie cartId = new Cookie("Shipping_cartId",
URLEncoder.encode(request.getParameter("cartId"),"UTF-8"));
Cookie name = new Cookie("Shipping_name",
URLEncoder.encode(request.getParameter("name"),"UTF-8"));
Cookie shippingDate = new Cookie("Shipping_shippingDate",
URLEncoder.encode(request.getParameter("shippingDate"),"UTF-8"));
Cookie country = new Cookie("Shipping_country",
URLEncoder.encode(request.getParameter("country"),"UTF-8"));
Cookie zipCode = new Cookie("Shipping_zipCode",
URLEncoder.encode(request.getParameter("zipCode"),"UTF-8"));
Cookie addressName = new Cookie("Shipping_addressName",
URLEncoder.encode(request.getParameter("addressName"),"UTF-8"));
//생성한 쿠키의 유효시간을 24시간으로 설정
cartId.setMaxAge(24*60*60);
name.setMaxAge(24*60*60);
shippingDate.setMaxAge(24*60*60);
country.setMaxAge(24*60*60);
zipCode.setMaxAge(24*60*60);
addressName.setMaxAge(24*60*60);
//쿠키를 등록하기 위해 response객체를 통해 클라이언트(크롬)에게 전달해 줌
response.addCookie(cartId);
response.addCookie(name);
response.addCookie(shippingDate);
response.addCookie(country);
response.addCookie(zipCode);
response.addCookie(addressName);
response.sendRedirect("orderConfirmation.jsp");
%>
<%@page import="java.net.URLDecoder"%>
<%@page import="dto.Product"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%
request.setCharacterEncoding("UTF-8");
String cartId = session.getId();
Cookie[] cookies = request.getCookies();
String shipping_cartId = "";
String shipping_name = "";
String shipping_shippingDate = "";
String shipping_country = "";
String shipping_zipCode = "";
String shipping_addressName = "";
// 쿠키가 있어야 함
if(cookies != null){
for(int i=0; i<cookies.length;i++){
Cookie thisCookie = cookies[i];
// 쿠키명을 가져오기
String n = thisCookie.getName();
// 쿠키명에 매핑되어 있는 값을 가져오기
if(n.equals("Shipping_cartId")){
shipping_cartId = URLDecoder.decode(thisCookie.getValue(),"UTF-8");
}
if(n.equals("Shipping_name")){
shipping_name = URLDecoder.decode(thisCookie.getValue(),"UTF-8");
}
if(n.equals("Shipping_shippingDate")){
shipping_shippingDate = URLDecoder.decode(thisCookie.getValue(),"UTF-8");
}
if(n.equals("Shipping_country")){
shipping_country = URLDecoder.decode(thisCookie.getValue(),"UTF-8");
}
if(n.equals("Shipping_zipCode")){
shipping_zipCode = URLDecoder.decode(thisCookie.getValue(),"UTF-8");
}
if(n.equals("Shipping_addressName")){
shipping_addressName = URLDecoder.decode(thisCookie.getValue(),"UTF-8");
}
}
}
%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/css/bootstrap.min.css">
<title>주문 정보</title>
</head>
<body>
<!-- top 인클루드 시작 -->
<jsp:include page="/ch03/top.jsp" />
<!-- top 인클루드 끝 -->
<div class="jumbotron">
<div class="container">
<h1 class="display-3">주문 정보</h1>
</div>
</div>
<!-- 배송에 관한 정보 시작 -->
<div class="container col-8 alert alert-info">
<div class="text-center">
<h1>영수증</h1>
</div>
<div class="row justify-content-between">
<div class="col-4" align="left">
<strong>배송 주소</strong><br>
성명 : <%=shipping_name%> <br>
우편번호 : <%=shipping_zipCode%> <br>
주소 : <%=shipping_addressName%>(<%=shipping_country%>)<br>
</div>
<div class="col-4" align="right">
<p><em>배송일 : <%=shipping_shippingDate %></em></p>
</div>
</div>
<!-- 배송에 관한 정보 끝 -->
<div>
<table class="table table-hover">
<tr>
<th class="text-center">상품</th>
<th class="text-center">#</th>
<th class="text-center">가격</th>
<th class="text-center">소계</th>
</tr>
<%
//장바구니는 세션을 사용한다(세션명 : cartlist)
List<Product> cartList = (List<Product>)session.getAttribute("cartlist");
%>
<c:set var="cartList" value="<%=cartList%>"/>
<!--상품에 관한 정보 시작-->
<c:forEach var="product" items="${cartList}">
<tr>
<td class="text-center"><em>${product.pname}</em></td>
<td class="text-center">${product.quantity}</td>
<td class="text-center"><fmt:formatNumber value="${product.uniPrice}" pattern="#,###"/>원</td>
<td class="text-center"><fmt:formatNumber value="${product.quantity * product.uniPrice}" pattern="#,###"/>원</td>
</tr>
<!-- sum으로 누적 -->
<c:set var="sum" value="${sum + product.quantity * product.uniPrice}" />
</c:forEach>
<tr>
<td></td>
<td></td>
<td><strong>총액 : </strong></td>
<td class="text-center text-danger"><strong><fmt:formatNumber value="${sum}" pattern="#,###"/>원</strong></td>
</tr>
</table>
<a href="shippingInfo.jsp?cartId=${param.cartId }" class="btn btn-secondary" role="button">이전</a>
<a href="thankCustomer.jsp" class="btn btn-success">주문완료</a>
<a href="checkOutCancelled.jsp" class="btn btn-secondary" role="button">취소</a>
</div>
</div>
<!-- bottom 인클루드 시작 -->
<jsp:include page="/ch03/bottom.jsp" />
<!-- bottom 인클루드 끝 -->
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/css/bootstrap.min.css" />
<title>주문 취소</title>
</head>
<body>
<!-- top 인클루드 시작 -->
<jsp:include page="/ch03/top.jsp" />
<!-- top 인클루드 끝 -->
<div class="jumbotron">
<div class="container">
<h1 class="display-3">주문 취소</h1>
</div>
</div>
<div class="container">
<h2 class="alert alert-danger">주문이 취소되었습니다.</h2>
</div>
<div class="container">
<p>
<a href="products.jsp" class="btn btn-secondary">»상품 목록</a>
</p>
</div>
<!-- bottom 인클루드 시작 -->
<jsp:include page="/ch03/bottom.jsp" />
<!-- bottom 인클루드 끝 -->
</body>
</html>
<%@page import="java.net.URLDecoder"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
Cookie[] cookies = request.getCookies();
String shipping_cartId = "";
String shipping_shippingDate = "";
if(cookies != null){
for(int i=0;i<cookies.length;i++){
Cookie thisCookie = cookies[i];
String n = thisCookie.getName();
if(n.equals("Shipping_cartId")){
shipping_cartId = URLDecoder.decode(thisCookie.getValue(),"UTF-8");
}
if(n.equals("Shipping_shippingDate")){
shipping_shippingDate = URLDecoder.decode(thisCookie.getValue(),"UTF-8");
}
}
}
%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/css/bootstrap.min.css" />
<title>주문 완료</title>
</head>
<body>
<!-- top 인클루드 시작 -->
<jsp:include page="/ch03/top.jsp" />
<!-- top 인클루드 끝 -->
<div class="jumbotron">
<div class="container">
<h1 class="display-3">주문 완료</h1>
</div>
</div>
<div class="container">
<h2 class="alert alert-danger">주문해주셔서 감사합니다.</h2>
<p>주문은 <%=shipping_shippingDate %> 에 배송될 예정입니다.</p>
<p>주문번호 : <%=shipping_cartId %> </p>
</div>
<div class="container">
<p>
<a href="products.jsp" class="btn btn-secondary">»상품 목록</a>
</p>
</div>
<!-- bottom 인클루드 시작 -->
<jsp:include page="/ch03/bottom.jsp" />
<!-- bottom 인클루드 끝 -->
</body>
</html>
<%
//세션으로 저장된 장바구니 정보를 모두 삭제함
session.invalidate();
//쿠키에 저장된 배송 정보를 모두 삭제함
for(int i=0;i<cookies.length;i++){
Cookie thisCookie = cookies[i];
// 쿠키명을 가져오기
String n = thisCookie.getName();
// 쿠키명에 매핑되어 있는 값을 가져오기
if(n.equals("Shipping_cartId")){
thisCookie.setMaxAge(0);
}
if(n.equals("Shipping_name")){
thisCookie.setMaxAge(0);
}
if(n.equals("Shipping_shippingDate")){
thisCookie.setMaxAge(0);
}
if(n.equals("Shipping_country")){
thisCookie.setMaxAge(0);
}
if(n.equals("Shipping_zipCode")){
thisCookie.setMaxAge(0);
}
if(n.equals("Shipping_addressName")){
thisCookie.setMaxAge(0);
}
response.addCookie(thisCookie);
}
%>
<%@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");
//세션으로 가져오면 object이므로 형변환 필수
//out.print("cartList 크기 : " + cartList.size());
//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);
//금액 = 가격 * 수량
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>
<td></td>
<td></td>
<td>총액</td>
<td><%=sum %></td>
<td></td>
</tr>
</table>
<a href="products.jsp" class="btn btn-secondary">» 쇼핑 계속하기</a>
</div>
</div>
<!-- bottom.jsp 인클루드 시작 -->
<jsp:include page="/ch03/bottom.jsp" />
<!-- bottom.jsp 인클루드 끝 -->
</body>
</html>