Study/JSP

JSP 쇼핑몰 MVC 모델2로 변경하기-3

토기발 2022. 5. 21. 23:03

지난번에 카테고리와 상품관련 기능을 변경 완료하였으니 이제 쇼핑몰 기능을 변경하겠습니다.

쇼핑몰은 쇼핑몰 메인/ 카트 추가/ 카트 삭제/카트 수정/ 카트 리스트/ 상품 리스트/ 상품 상세 기능이 있습니다.

개인 공부용이므로 잘못된 부분이 있으면 언제나 지적 환영합니다^_^~

 


ShopMallCommand.java

public class ShopMallCommand implements CommandIf {

	@Override
	public Object processCommand(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		CategoryDAO dao = new CategoryDAOImpl();
		List<CategoryDTO> clist = dao.listCate();
		HttpSession session = req.getSession();
		session.setAttribute("listCategory", clist);
		ProductList plist = ProductList.getInstance();
		List<ProductDTO> plist1 = plist.selectBySpec("hit");
		List<ProductDTO> plist2 = plist.selectBySpec("new");
		List<ProductDTO> plist3 = plist.selectBySpec("best");
		req.setAttribute("hit", plist1);
		req.setAttribute("new", plist2);
		req.setAttribute("best", plist3);
		return "WEB-INF/shop/display/mall.jsp";
	}

}

jsp파일은 dao를 쓰는 부분이 request.getAttribute()로 변경된 것뿐이라 생략한다.

먼저 카테고리 리스트를 불러오기 위해 CategoryDAOImpl()을 호출한다.

dao.listCate() 메서드를 실행하여 카테고리 리스트를 가져온다. 

그리고 getSession()으로 카테고리 리스트값을 세션에 저장한다.

ProductList는 Hashtable<String, List<ProductDTO>>를 만들기 위한 클래스이다.

상품 스펙별로 selectBySpec(String pspec) 메서드 안에 넣고 setAttribute()로 뿌려줄 준비를 한다.

 

ProductList.java

public class ProductList {
	private ProductList() {}
	private static ProductList instance = new ProductList();
	public static ProductList getInstance() {
		return instance;
	}

 

private 로 객체를 생성하고 메모리에 할당했다. 

이러한 방식을 싱글톤 패턴이라고 한다.

 

싱글톤(Singleton), getInstance() 메서드: 고정된 메모리영역을 사용하여 메모리 낭비를 줄이고 공통된 객체를 사용할 때 매번 객체를 새로 생성하지 않는 방식. 자바에서 객체를 새로 생성할때 new 연산자를 통하여 매번 메모리에 새로 할당을 하는데, 싱글톤 패턴은 기본 생성자 자체를 private으로 생성하여 new 연산자를 통해 생성하지 못하도록 제약을 둔다.

출처 : https://myhappyman.tistory.com/35 

 

 

 


mall_cgProdList.jsp (모델2)

<%		String code = request.getParameter("code");
		String cname = request.getParameter("cname");
		DecimalFormat df = new DecimalFormat("###,###");%>
<div align="center">
<h3>Welcome to My Mall</h3>
<%
			List<ProductDTO> plist1 = (List)request.getAttribute(code);
			if (plist1 == null || plist1.size() == 0){
				out.println("<b>"+cname+"상품이 없습니다.</b><br>");
			}else {%>					
			<hr color="green" width="80%">
			<font size="5"><%=cname%></font>
			<hr color="green" width="80%">
			<table border="0" width="100%" align="center">
				<tr>
<%			int count = 0; 
				String upPath = config.getServletContext().getRealPath("/images");
				for(ProductDTO pdto : plist1){%>
					<td align="center">
						<a href="mall_prodView.mall?pnum=<%=pdto.getPnum()%>&select=<%=code%>">
						<img src="<%=upPath%>/<%=pdto.getPimage()%>" width="80" height="60">
						</a>
						<br>
						<%=pdto.getPname()%><br>
						<font color="red"><%=df.format(pdto.getPrice())%></font>원<br>
						<font color="green">[<%=pdto.getPoint()%>]</font>point
					</td>	
<%				count++;
					if (count%3 == 0){%>
					</tr><tr>					
<%				}
				}%>
			</tr>								
			</table>
<%		} %>	
		</div>

jsp파일은 큰 변경점이 없어서 모델2만 올렸다.

 

 

MallcgProdListCommand.java

public class MallcgProdListCommand implements CommandIf {

	@Override
	public Object processCommand(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String code = req.getParameter("code");
		ProductList plist = ProductList.getInstance();
		List<ProductDTO> plist1 = plist.selectByCode(code);
		req.setAttribute(code, plist1);		
		return "WEb-INF/shop/display/mall_cgProdList.jsp";
	}

}

먼저 code값을 받아온다. 

그리고 ProductList.getInstance() 를 호출하여 plist.selectByCode(code) 를 실행한다.

setAttribute(code, plist1) 에 넣고 jsp에 뿌려준다.

-> List<ProductDTO> plist1 = (List)request.getAttribute(code);

 

 


MallProdViewCommand.java

public class MallProdViewCommand implements CommandIf {

	@Override
	public Object processCommand(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String pnum = req.getParameter("pnum");
		String select = req.getParameter("select");
		ProductList plist = ProductList.getInstance();
		ProductDTO dto = plist.getProduct(Integer.parseInt(pnum), select);
		req.setAttribute("getProduct", dto);
		return "WEB-INF/shop/display/mall_prodView.jsp";
	}

}

위와 특별히 다른 점이 없는...

pnum과 select값을 받아오고 plist값 받아오고 getProduct()메서드를 실행한다.

그 값을 dto에 받고 setAttribute()에 저장해 jsp에 뿌려준다.

 

 

 


mall_cartList.jsp (모델1)

<div align="center">
	<table width="100%" border="1">
		<tr class="m2">
			<td colspan="6" align="center">
				<h4>장바구니 보기</h4>
			</td>
		</tr>		
		<tr class="m1">
			<th width="10%">번호</th>
			<th width="30%">상품명</th>
			<th width="15%">수량</th>
			<th width="15%">단가</th>
			<th width="20%">금액</th>
			<th width="10%">삭제</th>
		</tr>
<jsp:useBean id="prolist" class="my.shop.mall.ProductList" scope="session"/>
<jsp:setProperty property="pool" name="prolist" value="<%=pool%>"/>
<jsp:useBean id="cart" class="my.shop.mall.CartBean" scope="session"/>
<jsp:setProperty property="plist" name="cart" value="<%=prolist%>"/>
<%
		List<ProductDTO> cartList = cart.listCart();	
		DecimalFormat df = new DecimalFormat("###,###");
		String upPath = request.getServletContext().getRealPath("/myshop/images");
		if (cartList == null || cartList.size() == 0){%>
		<tr>
			<td colspan="6">장바구니에 등록된 상품이 없습니다.</td>
		</tr>

mall_cartList.jsp (모델2)

<div align="center">
	<table width="100%" border="1">
		<tr class="m2">
			<td colspan="6" align="center">
				<h4>장바구니 보기</h4>
			</td>
		</tr>		
		<tr class="m1">
			<th width="10%">번호</th>
			<th width="30%">상품명</th>
			<th width="15%">수량</th>
			<th width="15%">단가</th>
			<th width="20%">금액</th>
			<th width="10%">삭제</th>
		</tr>
<%
		List<ProductDTO> cartList = (List)session.getAttribute("cart");
		DecimalFormat df = new DecimalFormat("###,###");
		String upPath = request.getServletContext().getRealPath("/images");
		if (cartList == null || cartList.size() == 0){%>
		<tr>
			<td colspan="6">장바구니에 등록된 상품이 없습니다.</td>
		</tr>

jsp:useBean과 pool은 모델2에서 삭제되었다. 
cartList는 모델 2에서는 session으로 받아서 뿌려주었다. 

카트에 담아야 하는 정보는 다음 페이지에 가더라도 사라지면 안되기 때문에 getParameter가 아닌 session으로 받아주어야 한다.

 


 

 

mall_cartAdd.jsp (모델1)

<%
		String pnum = request.getParameter("pnum");
		String select = request.getParameter("select");
		String pqty = request.getParameter("pqty");
		
		if (pnum==null || select==null || pqty==null || pnum.trim().equals("") 
			|| select.trim().equals("") || pqty.trim().equals("")){
				response.sendRedirect("mall.jsp");
				return;
		}
		   
		int res = cart.insertCart(Integer.parseInt(pnum), select, Integer.parseInt(pqty));
		if (res>0){%>
			<script type="text/javascript">
				alert("장바구니 리스트로 이동합니다.")
				location.href="mall_cartList.jsp"
			</script>	
<%	}else {%>
			<script type="text/javascript">
				alert("장바구니 담기 실패!! 관리자에게 문의하세요")
				location.href="mall.jsp"
			</script>
<%	} %>

뷰가 없어서 모델2에서는 jsp파일이 삭제되었다.

 

MallCartAddCommand.java

public class MallCartAddCommand implements CommandIf {

	@Override
	public Object processCommand(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String pnum = req.getParameter("pnum");
		String select = req.getParameter("select");
		String pqty = req.getParameter("pqty");
		ProductList plist = ProductList.getInstance();
		ProductDTO dto = plist.getProduct(Integer.parseInt(pnum), select);
		dto.setPqty(Integer.parseInt(pqty));
		HttpSession session = req.getSession();
		List<ProductDTO> cart = (List)session.getAttribute("cart");
		if (cart == null) cart = new ArrayList<ProductDTO>();
		for(ProductDTO cartDTO : cart) {
			if (dto.getPnum() == cartDTO.getPnum()) {
				cartDTO.setPqty(dto.getPqty() + cartDTO.getPqty());
				return "WEB-INF/shop/display/mall_cartList.jsp";
			}
		}
		cart.add(dto);
		session.setAttribute("cart", cart);
		return "WEB-INF/shop/display/mall_cartList.jsp";
	}

}

 

카트 관련은 dao파일을 만들지 않고 커멘드파일에 메서드를 집어넣어서 코드가 길어졌다.

먼저 pnum과 select, pqty값을 받아온다. 그리고 ProductList를 호출한다. 

getProduct()메서드를 실행 후 dto.setPqty()로 수량을 재설정한다.

getSession()을 이용하여 cart리스트값을 세션으로 저장한다. 

(이 때 카트가 없으면 새로운 카트 리스트를 생성한다.)

if문 안에 있는 내용은 만약 카트 안에 있는 상품과 같은 상품을 카트에 다시 담는다면 수량을 서로 더해주라는 뜻이다.

 

 


MallCartEditCommand.java

public class MallCartEditCommand implements CommandIf {

	@Override
	public Object processCommand(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		HttpSession session = req.getSession();
		List<ProductDTO> cart = (List)session.getAttribute("cart");
		int pnum = Integer.parseInt(req.getParameter("pnum"));
		int pqty = Integer.parseInt(req.getParameter("pqty"));
		if (pqty <= 0) {
			return "mall_cartDel.mall?pnum="+pnum;
		}else {
			for(ProductDTO cartDTO : cart) {
				if (pnum == cartDTO.getPnum()) {
					cartDTO.setPqty(pqty);
				}
			}
		}
		return "WEB-INF/shop/display/mall_cartList.jsp";
	}

}

 

먼저 세션에서 cart를 가져온다.

그리고 수정한 pnum값과 pqty값을 getParameter 로 가져온다. 

만약 수량이 0이하일 경우에는 카트에 담은 상품을 삭제한다. 

아니라면 변경한 수량으로 저장해준다.

 

 


MallCartDelCommand.java

public class MallCartDelCommand implements CommandIf {

	@Override
	public Object processCommand(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		int pnum = Integer.parseInt(req.getParameter("pnum"));
		HttpSession session = req.getSession();
		List<ProductDTO> cart = (List)session.getAttribute("cart");
		for(ProductDTO cartDTO : cart) {
			if (pnum == cartDTO.getPnum()) {
				cart.remove(cartDTO);
				break;
			}
		}
		return "WEB-INF/shop/display/mall_cartList.jsp";
	}

}

pnum을 getParameter로 가져온다.

cart를 세션에서 받는다. 

선택한 pnum이 카트에 있는 pnum과 같다면 삭제해준다.

 

 

 

 

JSP 쇼핑몰 MVC 모델2로 변경 끝!

게시판이랑 회원관리도 변경 연습 해봐야겠다.

'Study > JSP' 카테고리의 다른 글

JSP 쇼핑몰 MVC 모델2로 변경하기-2  (0) 2022.05.21
JSP 쇼핑몰 MVC 모델2 로 변경하기  (0) 2022.05.21