JSP - 모델1 방식으로 쇼핑몰 만들기(상품 리스트 구현) #4


오랜만에 돌아왔네요. 이번 시간에는 쇼핑몰의 상품 리스트를 구현하는 방법을 알아보도록 하겠습니다. 이번 편도 처음은 그렇게 어렵지 않습니다. 다음 편인 상품 구매나 장바구니에서 다소 할 것이 많아질 뿐... 이번 편은 의외로 짧게 끝날지도 모르겠네요.



필요한 파일 구성은 3가지입니다. 자세한 폴더 구조는 github(바로가기)에서 확인해주세요.

1. productlist.jsp
2. productMgr.java
3. productBean.java

우선 상품 목록 게시판인 productlist.jsp를 보겠습니다. body 에서 시작하여 상단과 하단에 <%@ include file="***" %> 의 형태로 메뉴와 관리자 정보를 넣었고 다음에 보면 ArrayList를 통해 productBean을 거쳐 ProductMgr로 가서 db를 가져오는 것을 볼 수 있습니다. 그리고 테이블을 만들어서 <td> 내부에 <%=p.getPrice() %> 와 같은 형태로 호출하는 것을 볼 수 있습니다. ArrayList이기 때문에 DB에 등록된 만큼 호출하는 방식인거죠.

<%@page import="pack.product.ProductBean"%>
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<jsp:useBean id="productMgr" class="pack.product.ProductMgr" />
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>상품목록</title>
<link href="../css/style.css" rel="stylesheet" type="text/css">
<script src="../js/script.js">
</script>
</head>
<body>
<h2>** 대한민국 쇼핑몰 **</h2>
<%@include file="guest_top.jsp" %>
<table style="width:90%">
     <Tr style="background-color: gold">
          <th>상품</th><th>가격</th><th>재고량</th><th>상세보기</th>
     </Tr>
     
     <%
     ArrayList<ProductBean> list = productMgr.getProductAll();
     
     for(ProductBean p:list){
     %>
     <tr style="text-align: center;">
          <td><img src="../data/<%=p.getImage()%>" width="70"><br><%=p.getName() %></td>
          <td><%=p.getPrice() %></td>
          <td><%=p.getStock() %></td>
          <td><a href="javascript:productDetail_guest('<%=p.getNo()%>')">보기</td>
     </tr>
     <%   
     }
     %>
</table>
<%@include file="guest_bottom.jsp" %>
<form action="productdetail_guest.jsp" name="detailFrm" method="post">
     <input type="hidden" name="no">
</form>
</body>
</html>

ProductBean은 말 그대로 getter, setter 정의해놓은 거라 특별한 건 없습니다. sql db에 넣은 칼럼 그대로 만들면 됩니다.

package pack.product;
public class ProductBean { // 상품 주문 관련
     private int no;
     private String name, price, detail, sdate, stock, image;
     
     public int getNo() {
          return no;
     }
     public void setNo(int no) {
          this.no = no;
     }
     public String getName() {
          return name;
     }
     public void setName(String name) {
          this.name = name;
     }
     public String getPrice() {
          return price;
     }
     public void setPrice(String price) {
          this.price = price;
     }
     public String getDetail() {
          return detail;
     }
     public void setDetail(String detail) {
          this.detail = detail;
     }
     public String getSdate() {
          return sdate;
     }
     public void setSdate(String sdate) {
          this.sdate = sdate;
     }
     public String getStock() {
          return stock;
     }
     public void setStock(String stock) {
          this.stock = stock;
     }
     public String getImage() {
          return image;
     }
     public void setImage(String image) {
          this.image = image;
     }
     
     
     
}


다음은 SQL을 호출하는 ProductMgr입니다. 여기서 필요한 것은 public ArrayList<ProductBean> getProductAll() 부분입니다. 그냥 ArrayList 형식으로 모든 db를 불러오게 됩니다.


package pack.product;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;

import pack.order.OrderBean;



public class ProductMgr {
    private Connection conn;
    private PreparedStatement pstmt;
    private ResultSet rs;
    private DataSource ds;
    
    
    public ProductMgr() {
        try {
            Context context = new InitialContext();
            ds = (DataSource)context.lookup("java:comp/env/jdbc_maria");
            
        } catch (Exception e) {
            System.out.println("ProductMgr err : " + e);
        }
    }
    
    public ArrayList<ProductBean> getProductAll(){
        ArrayList<ProductBean> list = new ArrayList<>();
        try {
            conn = ds.getConnection();
            String sql = "select * from shop_product order by no desc;";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            while(rs.next()) {
            ProductBean bean = new ProductBean();
            bean.setNo(rs.getInt("no"));
            bean.setName(rs.getString("name"));
            bean.setPrice(rs.getString("price"));
            bean.setDetail(rs.getString("detail"));
            bean.setSdate(rs.getString("sdate"));
            bean.setPrice(rs.getString("price"));
            bean.setStock(rs.getString("stock"));
            bean.setImage(rs.getString("image"));
            list.add(bean);                
            }
        } catch (Exception e) {
            System.out.println("ProductBean err:" + e);
        }finally {
            try {
                if(rs != null) rs.close();
                if(pstmt != null) pstmt.close();
                if(conn != null) conn.close();
            } catch (Exception e2) {
                // TODO: handle exception
            }    
        }
        return list;
    }
    
    public boolean insertProduct(HttpServletRequest request) {
        boolean b = false;
        try {
            //업로드할 이미지 경로(절대 경로)
            String uploadDir ="C:/Users/kitcoop/git/espriter_blog_practice_kic/espriter_blog_bbs/WebContent/data";
            //MultipartRequest multi=new MultipartRequest(request, savePath, sizeLimit, new DefaultFileRenamePolicy());
            MultipartRequest multi = new MultipartRequest(request, uploadDir, 5*1024*1024, "utf-8", new DefaultFileRenamePolicy());
            conn = ds.getConnection();
            String sql = "insert into shop_product(name, price, detail, sdate, stock, image) values(?,?,?,now(),?,?)"; //now는 sdate(지금) 의미
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,  multi.getParameter("name"));
            pstmt.setString(2,  multi.getParameter("price"));
            pstmt.setString(3,  multi.getParameter("detail"));
            //sdate는 입력 안해도 자체적으로 생성됨
            pstmt.setString(4,  multi.getParameter("stock"));
            if(multi.getFilesystemName("image") == null) {
                //신상품 이미지를 택하지 않았을 경우 디폴트 이미지 선택
                pstmt.setString(5, "../images/ready.gif");
            }else {
                pstmt.setString(5,  multi.getFilesystemName("image"));
            }            
            if(pstmt.executeUpdate() > 0) b = true;
            
        } catch (Exception e) {
            System.out.println("insertProduct err:" + e);
        }finally {
            try {
                if(rs != null) rs.close();
                if(pstmt != null) pstmt.close();
                if(conn != null) conn.close();
            } catch (Exception e2) {
                // TODO: handle exception
            }    
        }
        return b;
    }
    
    public ProductBean getProduct(String no) {
        ProductBean bean = null;
        try {
            conn = ds.getConnection();
            String sql = "select * from shop_product where no=?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, no);
            rs = pstmt.executeQuery();
            if(rs.next()) {
                bean = new ProductBean();
                bean.setNo(rs.getInt("no"));
                bean.setName(rs.getString("name"));
                bean.setPrice(rs.getString("price"));
                bean.setDetail(rs.getString("detail"));
                bean.setSdate(rs.getString("sdate"));
                bean.setStock(rs.getString("stock"));
                bean.setImage(rs.getString("image"));
            }        
        } catch (Exception e) {
            System.out.println("getProduct err:" + e);
        }finally {
            try {
                if(rs != null) rs.close();
                if(pstmt != null) pstmt.close();
                if(conn != null) conn.close();
            } catch (Exception e2) {
                // TODO: handle exception
            }    
        }
        return bean;
    }
    public boolean updateProduct(HttpServletRequest request) {
        boolean b = false;
        try {
            String uploadDir ="C:/Users/kitcoop/git/espriter_blog_practice_kic/espriter_blog_bbs/WebContent/data";
            //MultipartRequest multi=new MultipartRequest(request, savePath, sizeLimit, new DefaultFileRenamePolicy());
            MultipartRequest multi = new MultipartRequest(request, uploadDir, 5*1024*1024, "utf-8", new DefaultFileRenamePolicy());
            
            conn = ds.getConnection();
            
            if(multi.getFilesystemName("image") == null) {
                String sql ="update shop_product set name=?, price=?, detail=?, stock=? where no=?";
                pstmt = conn.prepareStatement(sql);
                pstmt.setString(1,multi.getParameter("name"));
                pstmt.setString(2,multi.getParameter("price"));
                pstmt.setString(3,multi.getParameter("detail"));
                pstmt.setString(4,multi.getParameter("stock"));
                pstmt.setString(5,multi.getParameter("no"));
                
            }else {
                String sql ="update shop_product set name=?, price=?, detail=?, stock=?, image=? where no=?";
                pstmt = conn.prepareStatement(sql);
                pstmt.setString(1,multi.getParameter("name"));
                pstmt.setString(2,multi.getParameter("price"));
                pstmt.setString(3,multi.getParameter("detail"));
                pstmt.setString(4,multi.getParameter("stock"));
                pstmt.setString(5,multi.getFilesystemName("image"));
                pstmt.setString(6,multi.getParameter("no"));
            }
            if(pstmt.executeUpdate() > 0 ) b = true;            
        } catch (Exception e) {
            System.out.println("updateProduct err:" + e);
        }finally {
            try {
                if(rs != null) rs.close();
                if(pstmt != null) pstmt.close();
                if(conn != null) conn.close();
            } catch (Exception e2) {
                // TODO: handle exception
            }    
        }
    
    return b;
}
    public boolean deleteProduct(String no) {
        boolean b = false;
        try {
            conn = ds.getConnection();
            String sql = "delete from shop_product where no=?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,no);
            if(pstmt.executeUpdate() > 0) b = true;
            
        } catch (Exception e) {
            System.out.println("deleteProduct err:" + e);
        }finally {
            try {
                if(rs != null) rs.close();
                if(pstmt != null) pstmt.close();
                if(conn != null) conn.close();
            } catch (Exception e2) {
                // TODO: handle exception
            }    
        }
                
        return b;
        
    }
    
    public void reduceProduct(OrderBean order) {
        try {
            conn = ds.getConnection();
            String sql = "update shop_product set stock=stock - ? where no=?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, order.getQuantity());
            pstmt.setString(2, order.getProduct_no());
            pstmt.executeUpdate();
        } catch (Exception e) {
            System.out.println("reduceProduct err:" + e);
        }finally {
            try {
                if(rs != null) rs.close();
                if(pstmt != null) pstmt.close();
                if(conn != null) conn.close();
            } catch (Exception e2) {
                // TODO: handle exception
            }    
        }
    }
    
}


그리하여 구현하면 아래와 같습니다. 여기서는 주문까지 구현이 되었는데 주문은 다음 시간에 계속됩니다.


감사합니다. 다음 편에 뵙겠습니다.



본 포스팅은 IT 교육기관인 KIC 캠퍼스에서 공부하며 작성한 리포트입니다.
혹시 잘못된 내용이 있거나 문제 소지시 댓글 남겨주시면 조치하겠습니다.





댓글(2)

Designed by CMSFactory.NET