[JSP] 쇼핑몰 만들기 (3)

·2023년 11월 6일
0

jsp

목록 보기
10/18

3. Display 페이지

(1) 화면 구성

📌 mall_top.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR" import="java.util.*, my.shop.*"%>
<% request.setCharacterEncoding("EUC-KR"); %>
    
<!-- mall_top.jsp -->
<jsp:useBean id="cdao" class="my.shop.CategoryDAO"/>
<jsp:useBean id="pool" class="my.db.ConnectionPoolBean" scope="application"/>
<jsp:setProperty name="cdao" property="pool" value="<%=pool%>"/>

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

<%	List<CategoryDTO> list = cdao.listCate(); 
	if (list == null || list.size() == 0){%>
		<script type="text/javascript">
			alert("쇼핑몰 준비중 입니다.")
			location.href="<%=request.getContextPath()%>/index.jsp"
		</script>
<%		return;
	}%>
<html>
<head>
	<title>쇼핑몰홈</title>
	<link rel="stylesheet" type="text/css" href="../../style.css">
</head>
<body>
	<div align="center">
		<table border="1" width="70%" height="90%">
			<tr height="10%">
				<td colspan="2" align="center">
					<a href="<%=request.getContextPath()%>/index.jsp">HOME</a> | 
					<a href="<%=request.getContextPath()%>/myshop/admin/main.jsp">관리자홈</a> | 
					<a href="<%=request.getContextPath()%>/myshop/display/mall.jsp">쇼핑몰홈</a> | 
					장바구니 | 
					<a href="<%=request.getContextPath()%>/company.jsp">회사소개</a>
				</td>
			</tr>
			<tr height="80%">
				<td width="20%" valign='top'>
					Tree/View
					<table border="1" width="100%">
<%					for(CategoryDTO dto : list){ %>					
						<tr>
							<td>
								<a href="javascript:prodList('<%=dto.getCode()%>','<%=dto.getCname()%>')">
									<%=dto.getCname()%>[<%=dto.getCode()%>]
								</a>	
							</td>
						</tr>
<%					}%>						
					</table>	
				</td>
				<td width="80%">
				
<form name="list" action="mall_cgProdList.jsp" method="post">
	<input type="hidden" name="code">
	<input type="hidden" name="cname">
</form>				
				

⭐ javascript 로 한글 처리하기

일반적인 a 태그와 get 방식으로 값을 넘겨서 카테고리 처리를 하려고 하면 갑자기 오류가 뜨는 걸 확인할 수 있다.
왜?

한글 처리를 제대로 못 할 때

이럴 때는 javascript 함수로 값을 넘겨줘서 한글 처리를 도울 수 있다.
아래 form 태그로 조그맣게 달아서 hidden 값으로 넘겨줘야 하는 값들을 처리하고

<form name="list" action="mall_cgProdList.jsp" method="post">
	<input type="hidden" name="code">
	<input type="hidden" name="cname">
</form>		

가장 위에 자바 스크립트 함수를 만들어 주자.

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

document 객체를 통해 웹 페이지의 요소에 접근하고 조작할 수 있으며, 예를 들어 HTML 요소를 찾고 내용을 변경하거나 새로운 요소를 생성할 수 있다.

📌 maill_bottom.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!-- mall_bottom.jsp -->
</td>
			</tr>
			<tr>
				<td colspan="2" align="center">
					Gahyun's SHOP				
				</td>
			</tr>
		</table>
	</div>
</body>
</htm

상대적으로 귀여운 bottom.jsp

📌 mall.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<% request.setCharacterEncoding("EUC-KR"); %>
    
<!-- mall.jsp -->
<%@ include file="mall_top.jsp" %>
<jsp:useBean id="productList" class="my.shop.mall.ProductList" scope="session"/>
<jsp:setProperty name="productList" property="pool" value="<%=pool%>"/>


<div align="center">
	<h2>Welcome to Gahyun's SHOP</h2>
	

<%
	java.text.DecimalFormat df = new java.text.DecimalFormat("###,###");
	String upPath = request.getServletContext().getRealPath("/myshop/images");
	List<ProductDTO> plist = productList.selectBySpec("hit");
	if (plist == null || plist.size() == 0){
		out.println("<b>HIT상품이 없습니다.</b>");
	}else {%>
		<hr color="green" width="300">
		<font color="red" size="3">HIT</font>
		<hr color="green" width="300">
		<table width="80%">
			<tr>
<%			int count = 0; 
			for(ProductDTO pdto : plist){
				count++;%>
				<td align="center">
					<a href="mall_prodView.jsp?pnum=<%=pdto.getPnum()%>&select=hit">
						<img src="<%=upPath%>/<%=pdto.getPimage()%>" 
													width="80" height="80">
					</a><br>
					<%=pdto.getPname()%><br>
					<font color="red"><%=df.format(pdto.getPrice())%></font><br>
					<font color="blue"><%=pdto.getPoint()%></font>point
				</td>
<%				if (count%3 == 0) {%>
			</tr><tr>
<%				}
			} %>						
			</tr>
		</table>	
<%	}
	List<ProductDTO> plist2 = productList.selectBySpec("new");
	if (plist2 == null || plist2.size() == 0){
		out.println("<b>NEW상품이 없습니다.</b>");
	}else {%>
		<hr color="green" width="300">
		<font color="red" size="3">NEW</font>
		<hr color="green" width="300">
		<table width="80%">
			<tr>
<%			int count = 0; 
			for(ProductDTO pdto : plist2){
				count++;%>
				<td align="center">
					<a href="mall_prodView.jsp?pnum=<%=pdto.getPnum()%>&select=new">
						<img src="<%=upPath%>/<%=pdto.getPimage()%>" 
													width="80" height="80">
					</a><br>
					<%=pdto.getPname()%><br>
					<font color="red"><%=df.format(pdto.getPrice())%></font><br>
					<font color="blue"><%=pdto.getPoint()%></font>point
				</td>
<%				if (count%3 == 0) {%>
			</tr><tr>
<%				}
			} %>						
			</tr>
		</table>	
<%	}
	List<ProductDTO> plist3 = productList.selectBySpec("best");
	if (plist3 == null || plist3.size() == 0){
		out.println("<b>BEST상품이 없습니다.</b>");
	}else {%>
		<hr color="green" width="300">
		<font color="red" size="3">BEST</font>
		<hr color="green" width="300">
		<table width="80%">
			<tr>
<%			int count = 0; 
			for(ProductDTO pdto : plist3){
				count++;%>
				<td align="center">
					<a href="mall_prodView.jsp?pnum=<%=pdto.getPnum()%>&select=best">
						<img src="<%=upPath%>/<%=pdto.getPimage()%>" 
													width="80" height="80">
					</a><br>
					<%=pdto.getPname()%><br>
					<font color="red"><%=df.format(pdto.getPrice())%></font><br>
					<font color="blue"><%=pdto.getPoint()%></font>point
				</td>
<%				if (count%3 == 0) {%>
			</tr><tr>
<%				}
			} %>						
			</tr>
		</table>	
<%	}
	List<ProductDTO> plist4 = productList.selectBySpec("normal");
	if (plist4 == null || plist4.size() == 0){
		out.println("<b>NORMAL상품이 없습니다.</b>");
	}else {%>
		<hr color="green" width="300">
		<font color="red" size="3">NORMAL</font>
		<hr color="green" width="300">
		<table width="80%">
			<tr>
<%			int count = 0; 
			for(ProductDTO pdto : plist4){
				count++;%>
				<td align="center">
					<a href="mall_prodView.jsp?pnum=<%=pdto.getPnum()%>&select=best">
						<img src="<%=upPath%>/<%=pdto.getPimage()%>" 
													width="80" height="80">
					</a><br>
					<%=pdto.getPname()%><br>
					<font color="red"><%=df.format(pdto.getPrice())%></font><br>
					<font color="blue"><%=pdto.getPoint()%></font>point
				</td>
<%				if (count%3 == 0) {%>
			</tr><tr>
<%				}
			} %>						
			</tr>
		</table>	
<%	}%>	
</div>	
<%@ include file="mall_bottom.jsp"%>	

📌 ProductList.java

package my.shop.mall;

import java.util.*;
import java.sql.*;

import my.db.ConnectionPoolBean;
import my.shop.*;

public class ProductList {
	private Hashtable<String, List<ProductDTO>> ht;
	Connection con;
	PreparedStatement ps;
	ResultSet rs;
	
	private ConnectionPoolBean pool;
	public void setPool(ConnectionPoolBean pool) {
		this.pool = pool;
	}
	public ProductList() {
		ht = new Hashtable<>();
	}
	
	public List<ProductDTO> selectBySpec(String pspec) throws SQLException{
		try {
			con = pool.getConnection();
			String sql = "select * from product where pspec = ?";
			ps = con.prepareStatement(sql);
			ps.setString(1, pspec);
			rs = ps.executeQuery();
			List<ProductDTO> list = makeList(rs);
			ht.put(pspec, list);
			return list;
		}finally {
			if (rs != null) rs.close();
			if (ps != null) ps.close();
			if (con != null) pool.returnConnection(con);
		}
	}   
}

⭐ productList 클래스 : sessoin 에 불러온 값을 저장

클라이언트가 페이지에 요청할 때마다 디비에 접근해 값을 불러와 다시 클라이언트에게 전달하는 과정은 서버 컴퓨터에 부담을 쉽게 줄 수 있다.
그렇다면 이러한 과정을 줄여서 클라이언트는 정보에 빠르게 접근할 수 있게 하고 서버는 귀찮은 일을 면하게 하면 어떨까?

이러한 방식을 구현하기 위해 다시 session 개념을 복습해 보자.
session에 클라이언트가 불러왔던 정보들을 hashtable로 저장해 둬 클라이언트가 필요로 할 때마다 빠르게 주는 것이다.

productList 클래스를 보면 hashtable 를 사용하고 있다.

미리 pspec에 해당하는 객체 리스트를 저장해 불러내기 쉽게 하는 것이다.

(2) 카테고리별 보기

📌 mall_cgProList.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
    
<% request.setCharacterEncoding("EUC-KR"); %>
    
<!-- mall_cgProdList.jsp -->
<%
	String code = request.getParameter("code");
	String cname = request.getParameter("cname");
	if (code == null || code.trim().equals("") || 
		cname == null || cname.trim().equals("")){
		response.sendRedirect("mall.jsp");
		return;
	}
%>	
<%@ include file="mall_top.jsp" %>
<jsp:useBean id="productList" class="my.shop.mall.ProductList" scope="session"/>
<jsp:setProperty name="productList" property="pool" value="<%=pool%>"/>
<div align="center">
<%
	java.text.DecimalFormat df = new java.text.DecimalFormat("###,###");
	String upPath = request.getServletContext().getRealPath("/myshop/images");
	List<ProductDTO> plist = productList.selectByCode(code);
	if (plist == null || plist.size() == 0){
		out.println("<b>"+cname+"상품이 없습니다.</b>");
	}else {%>
		<hr color="green" width="300">
		<font color="red" size="3"><%=cname%></font>
		<hr color="green" width="300">
		<table width="80%">
			<tr>
<%			int count = 0; 
			for(ProductDTO pdto : plist){
				count++;%>
				<td align="center">
					<a href="mall_prodView.jsp?pnum=<%=pdto.getPnum()%>&select=<%=code%>">
						<img src="<%=upPath%>/<%=pdto.getPimage()%>" 
													width="80" height="80">
					</a><br>
					<%=pdto.getPname()%><br>
					<font color="red"><%=df.format(pdto.getPrice())%></font><br>
					<font color="blue"><%=pdto.getPoint()%></font>point
				</td>
<%				if (count%3 == 0) {%>
			</tr><tr>
<%				}
			} %>						
			</tr>
		</table>	
<%	}%>
</div>	
<%@ include file="mall_bottom.jsp"%>

📌 ProductList : 카테고리 리스트 구현

	public List<ProductDTO> selectByCode(String code) throws SQLException{
		try {
			con = pool.getConnection();
			String sql = "select * from product where pcategory_fk like ?";
			ps = con.prepareStatement(sql);
			ps.setString(1, code+"%");
			rs = ps.executeQuery();
			List<ProductDTO> list = makeList(rs);
			ht.put(code, list);
			return list;
		}finally {
			if (rs != null) rs.close();
			if (ps != null) ps.close();
			if (con != null) pool.returnConnection(con);
		}
	}
	
	protected List<ProductDTO> makeList(ResultSet rs) throws SQLException {
		List<ProductDTO> list = new ArrayList<>();
		while(rs.next()) {
			ProductDTO dto = new ProductDTO();
			dto.setPnum(rs.getInt("pnum"));
			dto.setPname(rs.getString("pname"));
			dto.setPcategory_fk(rs.getString("pcategory_fk"));
			dto.setPcompany(rs.getString("pcompany"));
			dto.setPimage(rs.getString("pimage"));
			dto.setPqty(rs.getInt("pqty"));
			dto.setPrice(rs.getInt("price"));
			dto.setPspec(rs.getString("pspec"));
			dto.setPcontents(rs.getString("pcontents"));
			dto.setPoint(rs.getInt("point"));
			dto.setPinputdate(rs.getString("pinputdate"));
			list.add(dto);
		}
		return list;
	}

(3) 상품 상세 보기

📌 mall_prodView.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR" import="java.util.*, my.shop.*"%>

<% request.setCharacterEncoding("EUC-KR"); %>

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

<%
	int pnum = Integer.parseInt(request.getParameter("pnum"));
	String select = request.getParameter("select");
%>

<jsp:useBean id="productList" class="my.shop.mall.ProductList" scope="session"/>
<jsp:setProperty name="productList" property="pool" value="<%=pool%>"/>
<div align="center">

<%
	java.text.DecimalFormat df = new java.text.DecimalFormat("###,###");
	String upPath = request.getServletContext().getRealPath("/myshop/images");
	ProductDTO dto = productList.getProduct(pnum, select);
	if (dto == null){
		out.println("<b>"+ dto.getPname() +" 해당 상품이 없습니다.</b>");
	}else {%>
		<hr color="green" width="100%">
		[<%=dto.getPname()%>] 상품 상세 정보
		<hr color="green" width="100%">
		<table width="80%">
			<tr>
				<td><img src="<%=upPath%>/<%=dto.getPimage()%>" width="150" height="200"></td>
				<td align="left" valign='top'>
					상품 번호 : <%=dto.getPnum()%><br>
					상품 이름 : <%=dto.getPname()%><br>
					상품 가격 : <%=df.format(dto.getPrice())%><br>
					상품 포인트 : <%=df.format(dto.getPoint())%>point<br>
					상품 갯수 : <input type="text" name="num" style="width: 50px;"><br>
					<input type="submit" value="장바구니 담기">
					<input type="submit" value="즉시 구매하기">
				</td>	
			</tr>
			<tr>
				<td> 
				<h3>제품 상세 설명</h3>
				<%= dto.getPcontents()%>
				</td>
			</tr>
<%	}%>
		</table>	
</div>	
<%@ include file="mall_bottom.jsp"%>

📌 ProductList : 상품 상세 구현

	public ProductDTO getProduct(int pnum, String select) {
		List<ProductDTO> list = ht.get(select);
		for(ProductDTO dto : list) {
			if (dto.getPnum() == pnum) {
				return dto;
			}
		}
		return null;
	}
profile
자바 백엔드 개발자 개인 위키

0개의 댓글

관련 채용 정보