학원

쇼핑몰2 (목록처리(대문페이지 display),상세페이지 )

쿠룽지 2023. 12. 13. 09:00
728x90
반응형

 

 

-장바구니 담기가 있기 때문에 cart table도 생성한 것

-상품이 여러 개기 때문에 1 order - 多 product --> zorder_detail도 생성한 것

 

 


 

 

목록 작업

 

 

ItemDAO   작성

관리자/사용자 - 전체 상품 개수/검색 상품 개수

관리자/사용자 - 전체 상품 목록/검색 상품 목록

 

 

 

//관리자/사용자 - 전체 상품 개수/검색 상품 개수
public int getItemCount(String keyfield, String keyword, int status)throws Exception{
	Connection conn = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    String sql = null;
    String sub_sql = "";
    int count = 0;
    
    try{
    	conn = DBUtil.getConnection();
        //검색
        if(keyword!=null&&!"".equals(keyword)){
        	//검색처리
            if(keyfield.equals("1")) sub_sql += "AND name LIKE ?";
            else if(keyfield.equals("2")) sub_sql += "AND detail LIKE ?";
        }
        
        //SQL문 작성
        sql = "SELECT COUNT(*) FROM zitem WHERE status > ? " + sub_sql;
        
        pstmt = conn.preparedStatement(sql);
        
        pstmt.setInt(1, status);
        if(keyword!=null && !"".equals(keyword)){
        	pstmt.setString(2, "%"+keyword+"%");
        }
        rs = pstmt.executeQuery();
        if(rs.next()){
        	count = rs.getInt(1);
        }
    }catch(Exception e){
    	throw new Exception(e);
    }finally{
    	DBUtil.executeClose(rs, pstmt, conn);
    }
    return count;
}





//관리자/사용자 - 전체 상품 목록/검색 상품 목록
public List<ItemVO> getListItem(int start, int end, String keyfield, 
							String keyword, int status)throws Exception{
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		List<ItemVO> list = null;
		String sql = null;
		String sub_sql = "";
		int cnt = 0;
        
        try{
        	conn = DBUtil.getConnection();
            if(keyword!=null && !"".equals(keyword)){
            	if(keyfield.equals("1")) sub_sql += "AND name LIKE ?";
                else if(keyfield.equals("2")) sub_sql += "AND detail LIKE ?";
            }
            sql = "SELECT * FROM (SELECT a.*, rownum rnum FROM (SELECT * FROM zitem "
            + "WHERE status > ? " + sub_sql
            + "ORDER BY item_num DESC)a) WHERE rnum >=? AND rnum <= ?";
            
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(++cnt, status);
            if(keyword!=null && !"".equals(keyword)){
            	pstmt.setString(++cnt, "%"+keyword+"%");
            }
            pstmt.setInt(++cnt, start);
            pstmt.setInt(++cnt, end);
			//SQL문 실행
			rs = pstmt.executeQuery();
			list = new ArrayList<ItemVO>();
			while(rs.next()) {
				ItemVO item = new ItemVO();
				item.setItem_num(rs.getInt("item_num"));
				item.setName(rs.getString("name"));
				item.setPrice(rs.getInt("price"));
				item.setQuantity(rs.getInt("quantity"));
				item.setPhoto1(rs.getString("photo1"));
				item.setPhoto2(rs.getString("photo2"));
				item.setReg_date(rs.getDate("reg_date"));
				item.setStatus(rs.getInt("status"));
				
				list.add(item);            
        }catch(Exception e) {
			throw new Exception(e);
		}finally {
			DBUtil.executeClose(rs, pstmt, conn);
		}
		return list;
	}

 

 

 

 


 

 

사용자- 메인 페이지에 제품 보이게 (대문페이지)

 

 

style.css

/* 메인 (메인 페이지에 쇼핑몰 상품 보이게 하기)
------------------------------*/
.image-space .horizontal-area{
	margin:2px;
    padding:3px;
    width:220px;
    height:240px;
    float:left;
    overflow:hidden; /*흘러넘치는 데이터 처리*/
    text-align:center;
}
.image-space .horizontal-area img{
	width:215px;
    height:195px;
}
.image-space .float-clear{
	clear:both;
}

 

 

 

 

목록 읽어오기

kr.main.action

MainAction.java

package kr.main.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kr.controller.Action;
import kr.item.dao.ItemDAO;
import kr.item.vo.ItemVO;

public class MainAction implements Action{

	@Override
	public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
		//상품표시
        ItemDAO itemDao = ItemDAO.getInstance();
        List<ItemVO> itemList = itemDao.getListItem(1,16,null,null,1);
        
        request.setAttribute("itemList", itemList);
        
        return "/WEB-INF/views/main/main.jsp";
	}
}

 

List<ItemVO> itemList = itemDao.getListItem(1,16,null,null,1);

1페이지 16개 / (null, null) 검색 없이 모든 게시물 보여줌 / status가 1보다 큰 값만 읽어옴 

 

getListItem인자

(int start, int end, String keyfield, String keyword, int status)

 


 

 

main

main.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>메인</title>
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/style.css">
</head>
<body>
<div class="page-main">
	<jsp:include page="/WEB-INF/views/common/header.jsp"/>
	<div class="content-main">
		<h4>최신 상품</h4>
		<div class="image-space">
			<c:forEach var="item" items="${itemList}">
				<div class="horizontal-area">
					<a href="${pageContext.request.contextPath}/item/detail.do?item_num=${item.item_num}">
						<img src="${pageContext.request.contextPath}/upload/${item.photo1}">
						<span>${item.name}</span>
						<br>
						<b><fmt:formatNumber value="${item.price}"/>원</b>
					</a>
				</div>
			</c:forEach>
			<div class="float-clear">
				<hr width="100%" size="1" noshade="noshade">
			</div>
		</div>
	</div>
</div>
</body>
</html>

 

위 MainAction.java 에서

request.setAttribute("itemList", itemList) 라고 지정했기 때문에

여기서도 items="${itemList}" var="item" 이라고 설정, item.컬럼명 을 통해 값을 빼옴

 

 


 

 

 

 

 

 

상세 페이지 부분 처리

ItemDAO

//관리자/사용자 - 상품 상세
public ItemVO getItem(int item_num)throws Exception{
	
    Connection conn = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    ItemVO item = null;
    String sql = null;
    
    try{
    	conn = DBUtil.getConnection();
        sql = "SELECT * FROM zitem WHERE item_num=?";
        pstmt = conn.prepareStatement(sql);
        pstmt.setInt(1, item_num);
        
        rs = pstmt.executeQuery();
        if(rs.next()){
        	item = new ItemVO();
            item.setItem_num(rs.getInt("item_num"));
            item.setName(rs.getString("name"));
            item.setPrice(rs.getInt("price"));
            item.setQuantity(rs.getInt("quantity"));
            item.setPhoto1(rs.getString("photo1"));
            item.setPhoto2(rs.getString("photo2"));
            item.setDetail(rs.getString("detail"));
            item.setReg_date(rs.getDate("reg_date"));
            item.setStatus(rs.getInt("status"));
        }
    }catch(Exception e){
    	throw new Exception(e);
    }finally{
    	DBUtil.executeClose(rs, pstmt, conn);
    }
    return item;
}

상세정보 가져올 때

SELECT * FROM zitem WHERE item_num=? > setInt(1, item_num) 으로 행 선택 후

ItemVO 자바빈에 가져올 데이터 set, 자바빈 return 

 

 


 

 

 

모델 클래스

kr.item.action

UserDetailAction

package kr.item.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kr.controller.Action;
import kr.item.dao.ItemDAO;
import kr.item.vo.ItemVO;
import kr.util.StringUtil;

public class UserDetailAction implements Action{

	@Override
	public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
		//상품번호 반환
		int item_num = Integer.parseInt(
				               request.getParameter("item_num"));
		ItemDAO dao = ItemDAO.getInstance();
		ItemVO item = dao.getItem(item_num);
		
		//내용 줄바꿈 처리
		item.setDetail(StringUtil.useBrHtml(item.getDetail()));
		
		request.setAttribute("item", item);
		
		return "/WEB-INF/views/item/user_detail.jsp";
	}
}

 

dao-getItem 인자가 item_num 이기 때문에 item_num 을 request에서 빼내서 저장함

 

 

 

 


 

 

 

유저 - 상품 detail폼

 

상품 선택해서 장바구니(카트)에 담기 *로그인 필수

간발의 차 접속으로 데이터를 미표시라고 설정했던 상품을 표시라고 변경할 수 있기 때문에 그것 또한 수동 설정해야함

 

item

user_detail.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>  
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>상품 상세 정보</title>
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/style.css">
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-3.6.0.min.js"></script>
<script type="text/javascript">
$(function(){
	$('#order_quantity').on('keyup mouseup',function(){
		if($('#order_quantity').val()==''){
			$('#item_total_txt').text('총주문 금액 : 0원');
			return;
		}
		if($('#order_quantity').val()<=0){
			$('#order_quantity').val('');
			return;
		}
		if(Number($('#item_quantity').val()) < $('#order_quantity').val()){
			alert('수량이 부족합니다.');
			$('#order_quantity').val('');
			$('#item_total_txt').text('총주문 금액 : 0원');
			return;
		}
		
		let total = $('#item_price').val() * $('#order_quantity').val();
		$('#item_total_txt').text('총주문 금액 : ' + total.toLocaleString()+'원');
		
	});//end of on
	
	//장바구니 담기 이벤트 연결
	$('#item_cart').submit(function(event){
		if($('#order_quantity').val() == ''){
			alert('수량을 입력하세요');
			$('#order_quantity').focus();
			return false;
		}
		
		let form_data = $(this).serialize();
		//서버와 통신
		$.ajax({
			url:'${pageContext.request.contextPath}/cart/write.do',
			type:'post',
			data:form_data,
			dataType:'json',
			success:function(param){
				if(param.result == 'logout'){
					alert('로그인 후 사용하세요');
				}else if(param.result == 'success'){
					alert('장바구니에 담았습니다.');
					location.href='${pageContext.request.contextPath}/cart/list.do';
				}else if(param.result == 'overquantity'){
					alert('기존에 주문한 상품입니다. 개수를 추가하면 재고가 부족합니다.');
				}else{
					alert('장바구니 담기 오류');
				}
			},
			error:function(){
				alert('네트워크 오류 발생');
			}
		});
		//기본 이벤트 제거
		event.preventDefault();
	});
});
</script>
</head>
<body>
<div class="page-main">
	<jsp:include page="/WEB-INF/views/common/header.jsp"/>
	<div class="content-main">
		<c:if test="${item.status == 1}">
		<div class="result-display">
			<div class="align-center">
				본 상품은 판매 중지되었습니다.
				<p>
				<input type="button" value="판매상품 보기" onclick="location.href='itemList.do'">
			</div>
		</div>
		</c:if>
		<c:if test="${item.status == 2}">
		<h3 class="align-center">${item.name}</h3>
		<div class="item-image">
			<img src="${pageContext.request.contextPath}/upload/${item.photo2}" width="400">
		</div>
		<div class="item-detail">
			<form id="item_cart">
				<input type="hidden" name="item_num" value="${item.item_num}" id="item_num">
				<input type="hidden" name="item_price" value="${item.price}" id="item_price">
				<input type="hidden" name="item_quantity" value="${item.quantity}" id="item_quantity">
				<ul>
					<li>가격 : <b><fmt:formatNumber value="${item.price}"/>원</b></li>
					<li>재고 : <span><fmt:formatNumber value="${item.quantity}"/></span></li>
					<c:if test="${item.quantity > 0}">
					<li>
						<label for="order_quantity">구매수량</label>
						<input type="number" name="order_quantity" min="1" max="${item.quantity}" autocomplete="off"
						  id="order_quantity" class="quantity-width">
					</li>
					<li>
						<span id="item_total_txt">총주문 금액 : 0원</span>
					</li>
					<li>
						<input type="submit" value="장바구니에 담기">
					</li>
					</c:if>
					<c:if test="${item.quantity <= 0}">
					<li class="align-center">
						<span class="sold-out">품절</span>
					</li>
					</c:if>
				</ul>	                                             
			</form>
		</div>
		<hr size="1" noshade="noshade" width="100%">
		<p>
			${item.detail}
		</p>
		</c:if>
	</div>
</div>
</body>
</html>

 

c:if test = "${item.status==1}" - 판매중지 문구 출력

c:if test = "${item.status==2}" 일때 상품 상세정보 표시

상품명 ${item.name} 가격 ${item.price} 재고 ${item.quantity} 표시

 

 

주문할 상품 수량 결정 시

c:if test="${item.quantity>0}"

구매수량 type="number" min="1" max="${item.quantity}" id="order_quantity" 으로 올리면서 표시

 

위 jquery에서 order_quantity(구매수량).on ('keyup mouseup',function(){})을 걸어놔서

order_quantity.val()=='' 일때에는 $('#item_total_txt').text('총주문 금액 : 0원'); // 기본값

 

let total = $('#item_price').val() * $('#order_quantity').val();
$('#item_total_txt').text('총주문 금액 : ' + total.toLocaleString()+'원'); >> 로 주문금액 화면에서 바로 바뀜

 

 

form (id=item_cart).submit 이벤트 연결,

$.ajax를 통해 error 상황 제외하고 success 시 명시된 상황에 따라 값 출력+데이터 전송

 

 

 

 

 

 

 

728x90
반응형