ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 2022-01-26 jsp 쇼핑몰 만들기 #8
    학원/JSP SERVLET 2022. 1. 26. 16:40

     

    상품목록 뿐만아니라 주문목록, qna에서도 페이징을 사용해야하므로 productList.jsp에서 페이징을 위한 코드를 따로 만들어 각 페이지에 include 하는 방식으로 변경하고자 함 

     

     

    1) productList.jsp 수정 

     

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ include file="/admin/header.jsp" %>   
    <%@ include file="/admin/sub_menu.jsp" %>
    
    <article>
    
    <h1>상품 리스트</h1>
    <form name="frm" method="post">
    	<tr>
    		<td width="642"> 
    			상품명 <input type="text" name="key" value="${key}">
    			<input class="btn" type="button" name="btn_serach" value="검색" onClick="go_search();">
    			<input class="btn" type="button" name="btn_total" value="전체보기" onClick="go_total();">
    			<input class="btn" type="button" name="btn_write" value="상품 등록" onClick="go_wrt();">
    		</td>
    	</tr>
    </form>
    <table id="productList" >
    	<tr>
    		<th>번호</th>
    		<th>상품명</th>
    		<th>사입가</th>
    		<th>판매가</th>
    		<th>등록일</th>
    		<th>사용유무</th>
    	</tr>
    	<c:forEach items="${productList}" var="productVO">
    		<tr>
    			<td height="23" align="center"> ${productVO.pseq}</td>
    			<td style="text-align:left; padding-left:50px;">
    				<a href="#" onClick="go_detail('${productVO.pseq}');">${productVO.name}</a>
    			</td>
    			<td><fmt:formatNumber value="${productVO.price1}"/></td>
    			<td><fmt:formatNumber value="${productVO.price2}"/></td>
    			<td><fmt:formatDate value="${productVO.indate}"/></td>
    			<td><c:choose>
    				<c:when test='${productVO.useyn=="n"}'>미사용</c:when>
    				<c:otherwise>사용</c:otherwise>
    				</c:choose>
    	</c:forEach>
    </table>
    <br><br>
    
    <jsp:include page="/admin/paging/paging.jsp">
    	<jsp:param name="command" value="shop.do?command=adminProductList"/>
    </jsp:include>
    <!-- include로 paging.jsp를 불러 오면서 그 페이지에 파라미터로써 command 변수를 전달 -->
    <!-- command 이외에 변경될 값이 필요하다면 추가로 파라미터로 보내면 됨 -->
    <br><br>
    </article>
    
    <%@ include file="/admin/footer.jsp" %>

     

    정상적으로 작동 하지 않는다면 파라미터로 page, beginPage, endPage, prev, next 를 전부 보내는 방법도 있다. 

    -> 이경우 paging.jsp 에서 ${paging.page} 형식이 아니라 ${param.page} 형식으로 파라미터를 받아줘야 한다.

     

     

    2) /admin/paging/paging.jsp 

     

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <style type = "text/css">
    	body { text-aling:center;}
    	#paging{font-size:110%;}
    </style>
    </head>
    <body>
    <div id="paging" align="center" style="font-size:110%; font-wight:bold;">
        <c:url var="action" value="${param.command}"/>
        <c:if test="${paging.prev}">
            <a href="${action}&page=${paging.beginPage-1}">◀</a>&nbsp;
        </c:if>
    
        <c:forEach begin="${paging.beginPage}" end="${paging.endPage}" var="index">
            <c:choose>
                <c:when test="${paging.page==index}">
                    <span style="color:red">${index}&nbsp;</span>
                </c:when>
                <c:otherwise>
                    <a href="${action}&page=${index}&key=${key}">${index}</a> &nbsp;
                </c:otherwise>
            </c:choose>
        </c:forEach>
    
        <c:if test="${paging.next}">
            <a href="${action}&page=${paging.endPage+1}">▶</a>&nbsp;
        </c:if>
    </div>
    </body>
    </html>

     

     

    변경 해도 기능은 똑같이 적용 됨 ! 

     

     


     

    주문 목록 

     

    sub_menu에서 주문리스트를 클릭하면 command = adminOrderList 전달

     

    1) AdminOrderListAction

     

    public class AdminOrderListAction implements Action {
    
    	@Override
    	public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    		String url = "admin/order/orderList.jsp";
    		HttpSession session = request.getSession();
    		AdminVO avo = (AdminVO) session.getAttribute("loginAdmin");
    		
    		if(avo == null ) {
    			url = "shop.do?command=admin";
    		} else {
    			
    			int page=1;
    			if(request.getParameter("page")!=null) {
    				page = Integer.parseInt(request.getParameter("page"));
    				session.setAttribute("page", page);
    			} else if (session.getAttribute("page")!=null) {
    				page = (int) session.getAttribute("page");
    			} else {
    				page = 1;
    				session.removeAttribute("page");
    			}
    			
    			Paging paging = new Paging();
    			paging.setPage(page);
    			
    			AdminDao adao = AdminDao.getInstance();
    			
    			String key="";
    			if(request.getParameter("key")!=null) {
    				key = request.getParameter("key");
    				session.setAttribute("key", key);
    			} else if (session.getAttribute("key")!=null) {
    				key = (String)session.getAttribute("key");
    			} else {
    				session.removeAttribute("key");
    				key="";
    			}
    			
    			int count = adao.getAllCount("order_view", "mname", key);
    			
    			paging.setTotalCount(count);
    			request.setAttribute("paging", paging);
    			
    			ArrayList<OrderVO> orderList = adao.listOrder(paging,key);
    			request.setAttribute("orderList", orderList);
    			request.setAttribute("key", key);
    		}
    		request.getRequestDispatcher(url).forward(request, response);
    	}
    }

     

     

    2) listOrder() 메소드

     

    public ArrayList<OrderVO> listOrder(Paging paging, String key) {
        ArrayList<OrderVO> list = new ArrayList<>();
        String sql = "select * from ("
                + "select * from ("
                + "select rownum as rn, p.* from "
                + "((select * from order_view where mname like '%'||?||'%'"
                + " order by result, odseq desc) p)"
                + ") where rn >= ?) where rn<=?";
        con = Dbman.getConnection();
        try {
            pstmt = con.prepareStatement(sql);
            pstmt.setString(1, key);
            pstmt.setInt(2, paging.getStartNum());
            pstmt.setInt(3, paging.getEndNum());
            rs = pstmt.executeQuery();
            while(rs.next()) {
                OrderVO avo = new OrderVO();
                avo.setAddress(rs.getString("address"));
                avo.setId(rs.getString("id"));
                avo.setIndate(rs.getTimestamp("indate"));
                avo.setMname(rs.getString("mname"));
                avo.setOdseq(rs.getInt("odseq"));
                avo.setOseq(rs.getInt("oseq"));
                avo.setPhone(rs.getString("phone"));
                avo.setPname(rs.getString("pname"));
                avo.setPrice2(rs.getInt("price2"));
                avo.setPseq(rs.getInt("pseq"));
                avo.setQuantity(rs.getInt("quantity"));
                avo.setResult(rs.getString("result"));
                avo.setZip_num(rs.getString("zip_num"));
                list.add(avo);
            }
        } catch (SQLException e) { e.printStackTrace();
        } finally { Dbman.close(con, pstmt, rs); }
        return list;
    }

     

     

    3) orderList.jsp

     

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <%@ include file="/admin/header.jsp"%>
    <%@ include file="/admin/sub_menu.jsp"%>
    <article>
    <h1>주문리스트</h1>
    <form name="frm" method="post">
    <table style="float: right;">
    	<tr><td>주문자 이름
    		<input type="text" name="key" value="${key}" > 
    		    <input class="btn" type="button" value="검색" 	onClick="go_search(adminOrderList);">
    		    <input class="btn" type="button" name="btn_total" value="전체보기 " onClick="go_total(adminOrderList);">
    	    </td></tr>
    </table>
    </form>
    <table id="orderList">
    	<tr><th>주문번호(처리여부)</th><th>주문자</th><th>상품명</th><th>수량</th>
    	    <th>우편번호</th><th>배송지</th><th>전화</th><th>주문일</th></tr>
    	<c:forEach items="${orderList}" var="orderVO">
    		<tr><td><c:choose>
    			<c:when test='${orderVO.result=="1"}'>
    				<span style="font-weight: bold; color: blue">${orderVO.oseq}</span>
    				(<input type="checkbox" name="result" value="${orderVO.odseq}">미처리)</c:when>
    	    	<c:otherwise>
           			<span style="font-weight: bold; color: red">${orderVO.oseq}</span>
          			(<input type="checkbox" checked="checked" disabled="disabled">처리완료)</c:otherwise>
    			</c:choose></td>
    			<td>${orderVO.mname}</td><td>${orderVO.pname}</td><td>${orderVO.quantity}</td>
    			<td>${orderVO.zip_num}</td><td>${orderVO.address}</td> <td>${orderVO.phone}</td>
    			<td><fmt:formatDate value="${orderVO.indate}" /></td></tr>
    	</c:forEach>
    </table>
    
    <div class="clear"></div>
    <input type="button" class="btn" style="width: 200px" value="주문처리(입금확인)" onClick="go_order_save()">
    
    <br><br>
    <!-- 페이징 시작 -->
    <jsp:include page="/admin/paging/paging.jsp">
    	<jsp:param name="command" value="shop.do?command=adminOrderList" />
    </jsp:include>
    
    </article>
    
    <%@ include file="/admin/footer.jsp"%>

     

     

     

    4) go_search_order()와 go_total_order은 go_search, go_total() 과 기능이 같고 command변수 빼고 라인도 같으므로 

    go_search와 go_total에 command값을 받게 해 추가로 함수를 만들 필요가 없도록 한다.

     

    function go_search(comm){
    	if(document.frm.key.value == "") return;
    	var url = "shop.do?command=" + comm + "&page=1"; //검색결과의 1page로 이동
    	document.frm.action = url;
    	document.frm.submit();
    }
    
    function go_total(comm){
    	document.frm.key.value = "";
    	document.frm.action = "shop.do?command=" + comm + "&page=1";
    	document.frm.submit();
    }

     

     

    productList.jsp 에서 해당 부분을 수정

     

    -> 실수로 작은 따옴표 안씀... go_search('adminProductList') 형식으로 작성하도록

     

    검색 결과

     

     

     

    --> 검색어가 세션에 저장되어 있기 때문에 주문리스트에서 검색 후 서브 메뉴의 상품 리스트를 클릭하게 되면

     

     

     

    상품 리스트에서 해당 검색어를 검색한 결과가 출력된다.

     

    -> 서브 메뉴에서 상품리스트, 주문 리스트를 클릭했을 때 session의 key값을 초기화 해 줄 필요가 있음

    AdminProductList.java, AdminOrderList.java의 else문 안쪽 맨 위에 아래 코드를 추가한다.

     

    String sub = request.getParameter("sub");
    if(sub!=null) {
        session.removeAttribute("key");
        session.removeAttribute("page");
    }

     

    -> sub_menu.jsp도 수정

     

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <meta charset="UTF-8">
    <nav id="sub_menu">
    <h1>관리자 메뉴</h1>
    <ul>
    	<li><a href='shop.do?command=adminProductList&sub=y'>상품리스트</a></li>
    	<li><a href='shop.do?command=adminOrderList&sub=y'>주문리스트</a></li>
    	<li><a href='shop.do?command=adminMemberList&sub=y'>회원리스트</a></li>
    	<li><a href='shop.do?command=adminQnaList'>Q&amp;A리스트</a></li>
    
    </ul>
    
    </nav>

     

     


     

     

    주문 처리 (입금 확인)

     

    1) go_order_save() 함수

     

    function go_order_save(){
    	var count = 0;
    	if (document.frm.result.length==undefined) {
    	     if(document.frm.result.checked == true) count++;
    	} else {
    	  	for (var i = 0; i < document.frm.result.length; i++) {
    	    	if (document.frm.result[i].checked == true) count++;
    	    }
    	}  
    	
    	if (count == 0) {
    		alert("주문처리할 항목을 선택해 주세요.");
    	}else{
    		document.frm.action = "shop.do?command=adminOrderSave";
    		document.frm.submit();
    	} 
    }

     

     

    2) AdminOrderSaveAction 

     

    public class AdminOrderSaveAction implements Action {
    
    	@Override
    	public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		
    		String url = "shop.do?command=adminOrderList";
    		
    		HttpSession session = request.getSession();
    		AdminVO avo = (AdminVO)session.getAttribute("loginAdmin");
    		if( avo == null) { 
    			url = "shop.do?command=admin"; 
    		} else {
    			String[] resultArr = request.getParameterValues("result");
    			AdminDao adao = AdminDao.getInstance();
    			for(String odseq : resultArr) {
    				adao.updateOrderResult(odseq);
    			}
    		}
    		request.getRequestDispatcher(url).forward(request, response);
    	}
    }

     

     

     

    3) updateOrderResult(String odseq) 메서드

     

    public void updateOrderResult(String odseq) {
        String sql = "Update order_detail set result='2' where odseq=?";
        con = Dbman.getConnection();
        try {
              pstmt = con.prepareStatement(sql); 
              pstmt.setInt(1,  Integer.parseInt(odseq));
              pstmt.executeUpdate();
        } catch (Exception e) { e.printStackTrace();
        } finally { Dbman.close(con, pstmt, rs); }
    }

     

     

     

     

     

    에러1

     

     

     

     

    주문처리(입금확인) 버튼을 누르면 Uncaught ReferenceError: 가 등장 

    자바 스크립트가 문제인 것 같아 눈 빠지게 찾아봤더니 괄호가 잘못 여닫힘 

    -> 수정했더니 

     

    Uncaught TypeError: 가 ...

     

    다른 거 먼저 하자 하고 memberList 만들고 있었는데 갑자기 번뜩 생각남... 

     

     

    go_order_save()에 submit 버튼이 있음 = form이 필요함 

    근데 내가 form 을 저 위에서 닫아버림 후.. </form> 을 지웠더니 바로 해결됐다.

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

    댓글

Designed by Tistory.