[JSP] 홈페이지 만들기 (4)

·2023년 11월 8일
0

jsp

목록 보기
11/18

4. 장바구니 구현

(1) 장바구니 상품 추가

📌 mall_cartAdd.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!-- mall_cartAdd.jsp -->
<jsp:useBean id="cart" class="my.shop.mall.CartBean" scope="session"/>
<jsp:useBean id="productList" class="my.shop.mall.ProductList" scope="session"/>
<jsp:setProperty property="plist" name="cart" value="<%=productList%>"/>
<%
	String pnum = request.getParameter("pnum");
	String select = request.getParameter("select");
	String pqty = request.getParameter("pqty");
	if (pnum == null || pnum.trim().equals("") ||
		select == null || select.trim().equals("")){
		response.sendRedirect("mall.jsp");
		return;
	}
	if (pqty == null || pqty.trim().equals("")){%>
		<script type="text/javascript">
			alert("수량을 입력해 주세요!!")
			history.back()
		</script>	
<%		return;
	}
	int res = cart.addCart(Integer.parseInt(pnum), select, Integer.parseInt(pqty));
	String msg = null, url = null;
	if (res>0){
		msg = "장바구니 등록 성공!! 장바구니 리스트로 이동합니다.";
		url = "mall_cartList.jsp";
	}else {
		msg = "장바구니 등록 실패!! 장바구니 리스트로 이동합니다.";
		url = "mall.jsp";
	}
%>
<script type="text/javascript">
	alert("<%=msg%>")
	location.href="<%=url%>"
</script>

📌 cartBean.java

package my.shop.mall;
import java.util.*;
import my.shop.*;

public class CartBean {
	List<ProductDTO> listCart;
	
	private ProductList plist;

	public void setPlist(ProductList plist) {
		this.plist = plist;
	}
	
	public CartBean() {
		listCart = new ArrayList<>();
	}
	
	public int addCart(int pnum, String select, int pqty) {
		ProductDTO dto = plist.getProduct(pnum, select);
		//dto.setPqty(pqty);
		for(ProductDTO pdto : listCart) {
			if (dto.getPnum() == pdto.getPnum()) {
				pdto.setPqty(pdto.getPqty() + pqty);
				return 1;	//기존에 장바구니에 존재하는 상품
			}
		}
		//for문에 의해 return되지 않으면 장바구니에 없는 상품
		dto.setPqty(pqty);
		listCart.add(dto);
		return 1;
	}
}

⭐ 생각해 볼 것

장바구니 기능 개요
productList 에서 HashTable로 새션에 넣어 놨던 상품들 꺼내서 cartList에 저장한 후 새션을 통해 저장하는 것이다.
이러면 아주 쉽게 생각할 수 있음.

(2) 장바구니 상품 리스트

📌 mall_cartList.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR" import="java.util.*, my.shop.*"%>
<!-- mall_cartList.jsp -->
<jsp:useBean id="cart" class="my.shop.mall.CartBean" scope="session"/>
<%
	List<ProductDTO> cartList = cart.getListCart();
	if (cartList == null || cartList.size() == 0){%>
		<script type="text/javascript">
			alert("장바구니가 비었습니다. 쇼핑몰 페이지로 이동합니다.")
			location.href="mall.jsp";
		</script>
<%		return;
	} 
	String upPath = config.getServletContext().getRealPath("/myshop/images");
	java.text.DecimalFormat df = new java.text.DecimalFormat("###,###");
	int totalPrice = 0;
	int totalPoint = 0;
	%>	
<%@ include file="mall_top.jsp" %>

<script type="text/javascript">
	function prodList(code, cname){
			document.list.code.value = code
			document.list.cname.value = cname
			document.list.submit()	
	}
</script>

<div align="center">
	<table border="1">
		<tr>
			<td colspan="6" align="center" class="m2"><b>장바구니 보기</b></td>
		</tr>
		<tr>
			<th class="m1">번호</th>
			<th class="m1">상품명</th>
			<th class="m1">수량</th>
			<th class="m1">단가</th>
			<th class="m1">금액</th>
			<th class="m1">삭제</th>
		</tr>
<% 		for(ProductDTO dto : cartList){%>
		<tr>
			<td align="center"><%=dto.getPnum()%></td>
			<td align="center">
				<img src="<%=upPath%>/<%=dto.getPimage()%>" width="40" height="40"><br>
				<%=dto.getPname()%>
			</td>
			<td align="center">
				<form name="f" method="post" action="mall_cartEdit.jsp">
					<input type="text" name="pqty" value="<%=dto.getPqty()%>" size="3"><input type="hidden" name="pnum" value="<%=dto.getPnum()%>"/>
					<br>
					<input type="submit" value="수정">
				</form>
			</td>
			<td align="right">
				<%=df.format(dto.getPrice())%><br>
				[<%=dto.getPoint()%>]point
			</td>
			<td align="right">
				<font color="red">
					<%=df.format(dto.getPrice()*dto.getPqty())%><br>
					[<%=dto.getPoint()*dto.getPqty()%>]point
				</font>
			</td>
			<td align="center">
				<a href="mall_cartDel.jsp?pnum=<%=dto.getPnum()%>">삭제</a>
			</td>
		</tr>
<%			totalPrice += dto.getPrice() * dto.getPqty();
			totalPoint += dto.getPoint() * dto.getPqty();
		} %>
		<tr>
			<td colspan="4" align="left">
				<b>장바구니 총액 : <font color="red"><%=df.format(totalPrice)%></font></b><br>
				<font color="green">총 적립 포인트 : <%=totalPoint%>point</font>
			</td>
			<td colspan="2" align="center">
				[<a href="mall_order.jsp">주문하기</a>] 
				[<a href="mall.jsp">계속쇼핑</a>]
			</td>
		</tr>		
	</table>
</div>	
	


<%@ include file="mall_bottom.jsp"%>

📌 cartBean.java

	public List<ProductDTO> getListCart(){
		return listCart;
	}
	
	public int editCart(int pnum, int pqty) {
		if (pqty > 0) {
			for(ProductDTO pdto : listCart) {
				if (pdto.getPnum() == pnum) {
					pdto.setPqty(pqty);
					return 1;
				}
			}
		}
		int res = deleteCart(pnum);
		return res;
	}

(3) 장바구니 상품 삭제

📌 mall_cartDelete.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!-- mall_cartDel.jsp -->
<jsp:useBean id="cart" class="my.shop.mall.CartBean" scope="session"/>
<%
	String pnum = request.getParameter("pnum");
	if (pnum == null || pnum.trim().equals("")){
		response.sendRedirect("mall.jsp");
		return;
	}
	
	int res = cart.deleteCart(Integer.parseInt(pnum));
%>
<script type="text/javascript">
	alert("장바구니에서 상품을 삭제하였습니다.")
	location.href="mall_cartList.jsp"
</script>

📌 cartBean.java

	// 카트 리스트 삭제해 주기
	public int deleteCart(int pnum) {
		for(ProductDTO pdto : listCart) {
			if (pdto.getPnum() == pnum) {
				listCart.remove(pdto);
				return 1;
			}
		}
		return 0;
	}
    
    

(4) 장바구니 수정

📌 mall_cartEdit.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!-- mall_cartEdit.jsp -->
<jsp:useBean id="cart" class="my.shop.mall.CartBean" scope="session"/>
<%
	String pnum = request.getParameter("pnum");
	String pqty = request.getParameter("pqty");
	if (pnum == null || pnum.trim().equals("") || 
		pqty == null || pqty.trim().equals("")){
		response.sendRedirect("mall.jsp");
		return;
	}
	
	int res = cart.editCart(Integer.parseInt(pnum), Integer.parseInt(pqty));
%>
<script type="text/javascript">
	alert("장바구니에서 상품의 수량을 수정하였습니다.")
	location.href="mall_cartList.jsp"
</script>

📌 cartBean.java

	public int editCart(int pnum, int pqty) {
		if (pqty > 0) {
			for(ProductDTO pdto : listCart) {
				if (pdto.getPnum() == pnum) {
					pdto.setPqty(pqty);
					return 1;
				}
			}
		}
		int res = deleteCart(pnum);
		return res;
	}

jsp 너무 재미없다...
빨리 끝내고......... spring 해서 뭔가라도 찍어내 보고 싶다. 열심히 하고 싶다.
profile
자바 백엔드 개발자 개인 위키

0개의 댓글

관련 채용 정보