안녕하세요! 오늘은 도서를 주문했을 때 담길 장바구니 페이지를 만들어주려고 합니다. 도서 상세페이지에서 '주문하기'버튼을 클릭했을 때 장바구니에 담기도록 하고 버튼을 이용하여 장바구니 페이지로 넘어가도록 만들어 주었습니다. 그럼 장바구니 페이지에는 어떤 기능들이 필요할까요? 장바구니에는 삭제, 주문, 목록 버튼을 만들어서 각각이 구현되도록 만들어줄 것입니다. 그럼 시작해 볼까요?
📋순서
1. 변수 추가 & 상세페이지 수정
2. 장바구니 페이지 만들기
3. 결과
#01. 변수 추가&상세 페이지 수정
장바구니 페이지는 도서 상세페이지에서 넘어갈 수 있도록 만들어 줄 것입니다. 그러기 위해서는 도서 상세페이지 수정도 같이 해줘야 합니다.
1-1. 멤버 변수 추가해 주기
장바구니에 담은 상품의 개수를 관리하도록 dto / Product클래스에 다음과 같이 필드를 선언하여 주고 getter/setter을 선언하여 줍니다.
private int quantity; //장바구니에 담은 개수
//장바구니
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
1-2. 상품상세 정보 페이지 수정
도서 주문하기 버튼은 눌렀을 때, "장바구니에 추가하시겠습니까?"메시지가 뜨고 넘어갈 수 있도록 자바스크립트로 장바구니에 등록하기 위한 핸들러 함수 addToCart()를 작성합니다. 위치는 <head> 사이에 넣어주면 됩니다.
<script type="text/javascript">
function addToCart(){
if (confirm('상품을 장바구니에 추가하시겠습니까?')) {
document.addForm.submit();
} else {
document.addForm.reset();
}
}
</script>
name과 action속성값을 설정하도록 form태그를 작성합니다. 그리고 <도서 주문>을 클릭하면 핸들러 함수 addToCart()가 실행되도록 onclick속성을 작성합니다. <장바구니>를 클릭하면 웹페이지 cart.jsp가 실행되도록 작성하여 줍니다.
<p><form name="addForm" action="./addCart.jsp?id=<%=product.getBookID() %>" method="post">
<a href="#" class="btn btn-info" onclick="addToCart()">상품주문»</a>
<a href="./cart.jsp" class="btn btn-warning">장바구니»</a>
<a href="./products01.jsp" class="btn btn-secondary">상품목록»</a>
</form>
#02. 장바구니 페이지 만들기
2-1. 장바구니에 등록하는 페이지 작성
addCart.jsp페이지를 새로 생성해 주고 정보를 장바구니 페이지에 등록될 수 있도록 작성해 줍니다.
요청 파라미터 아이디를 전송받도록 request내장 객체의 getParameter() 메서드를 작성하고, 전송된 아이디가 없을 때 웹페이지 main.jsp로 이동하도록 response 내장 각페의 sendRedirect() 메서드를 작성합니다.
<%
String id = request.getParameter("id");
if (id == null || id.trim().equals("")) {
response.sendRedirect("main.jsp");
return;
}
%>
if문이 끝나고 괄호로 닫아준 밑에 줄에 다음과 같이 추가해줍니다. 상품데이터 접근 클래스 ProductRepository의 기본 생성자에 대한 객체 변수 instance를 얻어오도록 추가 작성해 주세요.
ProductRepository dao = ProductRepository.getInstance();
그리고 계속 그 밑에 이어서 작성을 해주면 되는데요. 상품아이디에 대한 상품 정보를 얻어오도록 ProductRepository객체의 getProductById() 메서드를 호출하고 이를 Product객체에 저장하도록 작성해 줍니다. 만약 상품 아이디에 대한 상품 정보가 없으면 이전에 만들어 두었던 예외처리 웹 페이지 exceptionNoProductId.jsp페이지로 이동하도록 response 내장 객체의 sendRedirect() 메서드로 작성합니다.
Product book = dao.getProductById(id);
if (book == null) {
response.sendRedirect("exceptionNoBookId.jsp");
}
상품 목록을 얻어오도록 ProductRepository객체의 getAllProducts()메소드를 호출하고 이를 ArratList객체에 저장하도록 작성합니다. ArrayList객체에 저장된 상품목록에 요청 파라미터 아이디의 상품이 존재하는지 검사하도록 작성합니다.
ArrayList<Product> goodsList = dao.getAllProducts();
Product goods = new Product();
for (int i = 0; i < goodsList.size(); i++) {
goods = goodsList.get(i);
if (goods.getBookID().equals(id)) {
break;
}
}
요청 파라미터 아이디의 상품을 담은 장바구니를 초기화하도록 작성합니다. 29행에서는 세션 속성 이름 cartlist(장바구니)의 세션 정보를 얻어와 ArratList객체에 저장합니다. 만약 ArrayList객체에 저장된 세션정보가 없으면 ArrayList객체를 생성하고 이를 세션 속성이름 cartlist의 속성 값으로 저장합니다.
ArrayList<Product> list = (ArrayList<Product>) session.getAttribute("cartlist");
if (list == null) {
list = new ArrayList<Product>();
session.setAttribute("cartlist", list);
}
전체적인 코드는 다음과 같습니다. 위에서 설명하지 않은 for부분은 요청 파라미터 아이디의 상품이 장바구니에 담긴 목록이면 해당 도서의 수량을 증가시키도록 작성하였습니다.
▶ addCart.jsp
<%@ page contentType="text/html; charset=utf-8"%>
<%@ page import="java.util.ArrayList"%>
<%@ page import="dto.Product" %>
<%@ page import="dao.ProductRepository" %>
<%
String id = request.getParameter("id");
if (id == null || id.trim().equals("")) {
response.sendRedirect("main.jsp");
return;
}
ProductRepository dao = ProductRepository.getInstance();
Product book = dao.getProductById(id);
if (book == null) {
response.sendRedirect("exceptionNoBookId.jsp");
}
ArrayList<Product> goodsList = dao.getAllProducts();
Product goods = new Product();
for (int i = 0; i < goodsList.size(); i++) {
goods = goodsList.get(i);
if (goods.getBookID().equals(id)) {
break;
}
}
ArrayList<Product> list = (ArrayList<Product>) session.getAttribute("cartlist");
if (list == null) {
list = new ArrayList<Product>();
session.setAttribute("cartlist", list);
}
int cnt = 0;
Product goodsQnt = new Product();
for (int i = 0; i < list.size(); i++) {
goodsQnt = list.get(i);
if (goodsQnt.getBookID().equals(id)) {
cnt++;
int orderQuantity = goodsQnt.getQuantity() + 1;
goodsQnt.setQuantity(orderQuantity);
}
}
if (cnt == 0) {
goods.setQuantity(1);
list.add(goods);
}
response.sendRedirect("product.jsp?id=" + id);
%>
2-2. 장바구니 페이지 작성하기
cart.jsp페이지를 생성해 주고 다음과 같이 작성해 줍니다.
▶ cart.jsp
<%@ page contentType="text/html; charset=utf-8"%>
<%@ page import="java.util.ArrayList"%>
<%@ page import="dto.Product" %>
<%@ page import="dao.ProductRepository" %>
<html>
<head>
<!-- Favicon -->
<link href="img/favicon.ico" rel="icon">
<!-- Google Web Fonts -->
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Poppins&family=Roboto:wght@700&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR&display=swap" rel="stylesheet">
<!-- Icon Font Stylesheet -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.4.1/font/bootstrap-icons.css" rel="stylesheet">
<link href="lib/flaticon/font/flaticon.css" rel="stylesheet">
<!-- Libraries Stylesheet -->
<link href="lib/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet">
<!-- Customized Bootstrap Stylesheet -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Template Stylesheet -->
<link href="css/style.css" rel="stylesheet">
<%
String cartId = session.getId();
%>
<title>장바구니</title>
</head>
<body>
<jsp:include page="menu.jsp" />
<div class="jumbotron" style="padding-top: 50px; padding-bottom: 50px">
<div class="container">
<h2>장바구니</h2>
</div>
</div>
<div class="container">
<div class="row" style="background-color: #f7f7f7; border-radius: 20px; height: 75px;">
<table width="100%" style="margin: 10px;">
<tr>
<td style="padding-left: 10px;"><input type="checkbox" id="allChk" checked> <b>전체</b></td>
<td></td>
<td align="right" style="padding-right: 35px;">
<a href="./deleteCart.jsp?cartId=<%=cartId%>"
class="btn btn-danger">삭제하기</a>
<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>
<th>비고</th>
</tr>
<%
int sum = 0;
ArrayList<Product> cartList = (ArrayList<Product>) session.getAttribute("cartlist");
if (cartList == null)
cartList = new ArrayList<Product>();
for (int i = 0; i < cartList.size(); i++) { // 상품리스트 하나씩 출력하기
Product book = cartList.get(i);
int total = book.getUnitPrice() * book.getQuantity();
sum = sum + total;
%>
<tr>
<td><input type="checkbox" class="chk" checked></td>
<td><%=book.getBookID() %> - <%=book.getBookName() %></td>
<td><%=book.getUnitPrice()%></td>
<td><%=book.getQuantity()%></td>
<td><%=total%></td>
<td>
<a href="./removeCart.jsp?id=<%=book.getBookID()%>"
class="bi bi-backspace-fill"> 삭제</a></td>
</tr>
<%
}
%>
<tr>
<th></th>
<th></th>
<th>총액</th>
<th><%=sum%></th>
<th></th>
<th></th>
</tr>
</table>
<a href="./books.jsp" class="btn btn-secondary"> « 쇼핑 계속하기</a>
</div>
<hr>
</div>
<!-- footer -->
<%@ include file="footer.jsp"%>
<!-- Back to Top -->
<a href="#" class="btn btn-primary py-3 fs-4 back-to-top"><i class="bi bi-arrow-up"></i></a>
<!-- JavaScript Libraries -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="lib/easing/easing.min.js"></script>
<script src="lib/waypoints/waypoints.min.js"></script>
<script src="lib/owlcarousel/owl.carousel.min.js"></script>
<!-- Template Javascript -->
<script src="js/main.js"></script>
<!-- Cart -->
<script src="js/cart.js"></script>
</body>
</html>
#03. 결과
'📒 개발기록 > JSP 프로젝트' 카테고리의 다른 글
[JSP][도서쇼핑몰 프로젝트]#12.주문처리페이지 만들기 (0) | 2023.03.26 |
---|---|
[JSP][도서쇼핑몰 프로젝트]#11.장바구니 페이지 만들기(2) (0) | 2023.02.20 |
[JSP][도서쇼핑몰 프로젝트]#9.로그 기록하기 (0) | 2023.02.10 |
[JSP][도서쇼핑몰 프로젝트]#8.예외처리 페이지 만들기 (0) | 2023.02.06 |
[JSP][도서쇼핑몰 프로젝트]#7.페이지 디자인 구상 (1) | 2023.01.31 |