< 제품 리스트 / 장바구니 만들기 + db 연결 >
* db에 data 셋팅
- 테이블 생성(sql)
CREATE TABLE PRODUCT
(pno number(7),
pname varchar2(50),
price number(10),
dcratio number(3),
prodesc varchar2(100),
qty number(8),
imgfile varchar2(100),
bigfile varchar2(100));
- 시퀀스 생성(sql)
CREATE SEQUENCE PRODUCT_PNO_SEQ
START WITH 1
INCREMENT BY 1
NOCACHE
NOCYCLE;
- data 파일 cmd에 저장
insert into product values (PRODUCT_PNO_SEQ.NEXTVAL, '상품명',
판매가격, 할인비율, '제품상세', 수량, '이미지파일경로', '큰이미지파일경로');
> select count(*) from product; 총 갯수 확인! > 커밋!!
* VO 생성 : [ProductVO]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
package vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ProductVO {
int pno;
String pname;
int price;
int dcratio;
String prodesc;
int qty;
String imgfile;
String bigfile;
}
|
cs |
* DAO 생성 : [ProductDAO]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
|
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;
import vo.ProductVO;
public class ProductDAO {
// 1~3 기본 생성자
String driver = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:@localhost:1521:orcl";
String user = "scott";
String password = "tiger";
Connection conn ;
PreparedStatement pstmt ;
ResultSet rs ;
StringBuffer sb = new StringBuffer();
public ProductDAO() {
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, user, password);
System.out.println("conn : "+conn);
} catch (ClassNotFoundException e) {
System.out.println("드라이버 로딩 실패");
} catch (SQLException e) {
System.out.println("DB 연결 실패");
}
} // 생성자 end
// 전체 조회
public ArrayList<ProductVO> selectAll(){
ArrayList<ProductVO> list = new ArrayList<ProductVO>();
sb.append("SELECT * FROM product");
try {
pstmt = conn.prepareStatement(sb.toString());
rs = pstmt.executeQuery();
while(rs.next()) {
int pno = rs.getInt("pno");
String pname = rs.getString("pname");
int price = rs.getInt("price");
int dcratio = rs.getInt("dcratio");
String prodesc = rs.getString("prodesc");
int qty = rs.getInt("qty");
String imgfile = rs.getString("imgfile");
String bigfile = rs.getString("bigfile");
ProductVO vo = new ProductVO(pno, pname, price, dcratio, prodesc, qty, imgfile, bigfile);
list.add(vo);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
} // selectAll() end
public ProductVO getOne(int pno){
sb.setLength(0);
sb.append("SELECT * FROM product WHERE pno = ? ");
ProductVO vo = null;
try {
pstmt = conn.prepareStatement(sb.toString());
pstmt.setInt(1, pno);
rs = pstmt.executeQuery();
while(rs.next()) {
String pname = rs.getString("pname");
int price = rs.getInt("price");
int dcratio = rs.getInt("dcratio");
String prodesc = rs.getString("prodesc");
int qty = rs.getInt("qty");
String imgfile = rs.getString("imgfile");
String bigfile = rs.getString("bigfile");
vo = new ProductVO(pno, pname, price, dcratio, prodesc, qty, imgfile, bigfile);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return vo;
}
public ArrayList<ProductVO> getData(Set<Integer> key) {
ArrayList<ProductVO> list = new ArrayList<ProductVO>();
// 1. set 계열의 데이터를 1개씩 꺼내서 출력
Iterator<Integer> it= key.iterator();
while(it.hasNext()) {
int pno = it.next();
// 꺼낸 데이터를 가지고 db에 접속해서 상품 정보를 얻어오기
ProductVO vo = getOne(pno);
list.add(vo);
}
return list;
}
}
|
cs |
- [TestMain2.java] : vo, dao, db 테스트 > 콘솔로 제품(데이터) 리스트 확인 가능
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
package vo;
import java.util.ArrayList;
import dao.ProductDAO;
public class TestMain2 {
public static void main(String[] args) {
ProductDAO dao = new ProductDAO();
ArrayList<ProductVO> list = dao.selectAll();
for(ProductVO vo : list) {
System.out.println(vo.getPno() + " : " + vo.getPname());
}
}
}
|
cs |
* 제품 리스트(쇼핑몰)과 제품 상세 페이지 만들기
- [productList.jsp] : 제품 리스트(쇼핑몰)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
|
<%@page import="java.util.ArrayList"%>
<%@page import="vo.ProductVO"%>
<%@page import="dao.ProductDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>productList.jsp</title>
<style>
* {
margin: 0; padding: 0;
}
#container{
width: 1000px;
margin: auto;
}
img{ width: 200px; height: 200px; }
p {
text-align: center;
}
.wrap{
width: 200px;
border: 1px solid red;
float: left;
padding: 20px;
margin: 2px;
}
.del{
text-decoration: line-through;
}
</style>
</head>
<body>
<div id="container">
<%
ProductDAO dao = new ProductDAO();
ArrayList<ProductVO> list = dao.selectAll();
for(ProductVO vo : list) {
// 상품 이름의 길이가 너무 길면(8자 까지만)
// 상품명... <--
// 1. 상품명 구하기
System.out.println(vo.getPname());
// 2. 상품명 길이 구하기
System.out.println(vo.getPname().length());
// 3. 이 길이가 8자 이상이면 8자 까지만 출력하게 하기
System.out.println((vo.getPname().length() >=12)?vo.getPname().substring(0,12)+"...":vo.getPname());
vo.setPname((vo.getPname().length() >=12)?
vo.getPname().substring(0,12)+"...":vo.getPname());
%>
<div class = "wrap">
<a href="productDetail.jsp?pno=<%=vo.getPno()%>"><img src="<%=vo.getImgfile() %>" alt="" /></a>
<p><%= vo.getPname() %></p>
<p class="del"><%= vo.getPrice() %></p>
<p>대박할인</p>
<p><%= vo.getDcratio() %></p>
<p><%= Math.round(vo.getPrice()*(1-vo.getDcratio()*0.01)) %>원 </p>
<p>
<input type="button" value="즉시구매" />
<input type="button" value="장바구니" />
</p>
</div>
<%
}
%>
</div>
</body>
</html>
|
cs |
- [productDetail.jsp] : 제품 상세 페이지
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
|
<%@page import="vo.ProductVO"%>
<%@page import="dao.ProductDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>productDetail.jsp</title>
<style>
#container{
width: 1000px;
margin: auto;
}
#pic{
width: 500px;
float: left;
}
table{
width: 100%;
border-top: 3px solid gray;
border-bottom: 3px solid gray;
}
#info{
width: 500px;
float: left;
}
div#pic>img{
width: 100%;
height: 50%:
}
#desc{
/*float 기능 제거 */
clear: both;
}
.icon{
width: 50px;
height: 50px;
}
</style>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("img[src='../images/cart.png']").on("click",function(){
$("#showImg").show();
window.setTimeout(function(){
document.frm.action="cart.jsp";
document.frm.method="get";
document.frm.submit();
}, 2000);
})
})
</script>
</head>
<body>
<h1>제품 상세보기</h1>
<%-- 상품의 상세정보 --%>
<%
String p = request.getParameter("pno");
if (p != null) {
int pno = Integer.parseInt(p);
ProductDAO dao = new ProductDAO();
ProductVO vo = dao.getOne(pno);
out.println("<h2> 상품명 : "+ vo.getPname() + "</h2>" );
%>
<div id="container">
<form action="" name="frm">
<input type="hidden" name="pno" id="pno" value="<%= vo.getPno() %>" />
</form>
<div id="pic">
<img src="<%=vo.getBigfile()%>" alt="<%=vo.getBigfile()%>" />
</div>
<div id="info">
<table>
<tr>
<td colspan="2"><%=vo.getPname()%></td>
</tr>
<tr>
<td>판매가격</td>
<td><%=vo.getPrice()%></td>
</tr>
<tr>
<td>할인가격</td>
<td><%=Math.round(vo.getPrice() * (1 - vo.getDcratio() * 0.01))%></td>
</tr>
<tr>
<td colspan="2">
<img class="icon" src="../images/payment.png" alt="" />
<img class="icon" src="../images/cart.png" alt="" id="cart"/>
<a href="viewCart.jsp">장바구니 보러가기</a>
</td>
</tr>
</table>
</div>
<div id="desc">
<p><%=vo.getProdesc() %></p>
</div>
<div id="showImg" style="display: none;">
<h1>장바구니에 넣었습니다.</h1>
<a href="javascript:closeDiv()">[닫기]</a>
</div>
</div>
<%
}
%>
</body>
</html>
|
cs |
* 장바구니
- [cart.jsp] : 장바구니 배열에 선택한 제품 추가
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
<%@page import="java.util.ArrayList"%>
<%@page import="vo.ProductVO"%>
<%@page import="dao.ProductDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>cart.jsp</title>
</head>
<body>
<%
// 파라미터 값 가져오기
String p = request.getParameter("pno");
// 현재 세션에서 cart라는 이름의 속성 객체를 얻어오기
// session.setAttribute("속성명", "값");
// session.getAttribute("속성명");
Object obj = session.getAttribute("cart");
// 만약 cart라는 속성이 없다면 하나 만들어줌
if(obj == null){
// ArrayList 생성
ArrayList<Integer> cart = new ArrayList<Integer>();
// 세션의 속성으로 지정
session.setAttribute("cart", cart);
// 세션에서 속성 가져오기
obj = session.getAttribute("cart");
}
// ArrayList로 형변환
ArrayList<Integer> cart = (ArrayList<Integer>)obj;
if(p != null) {
int pno = Integer.parseInt(p);
// 카트(ArrayList에 추가)
cart.add(pno);
System.out.println("cart : "+cart);
response.sendRedirect("productDetail.jsp?pno="+pno);
/* ProductDAO dao = new ProductDAO();
ProductVO vo = dao.getOne(pno); */
// out.println("<h2>상품명 : "+vo.getPname()+"</h2>");
} else { // p가 널이야 그럼 처음으로 돌아가
response.sendRedirect("productList.jsp");
}
%>
</body>
</html>
|
cs |
- [viewCart.jsp] : 카트 데이터 확인
>> productDAO에 getData 추가..
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
|
<%@page import="java.util.Set"%>
<%@page import="vo.ProductVO"%>
<%@page import="dao.ProductDAO"%>
<%@page import="java.util.HashMap"%>
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>viewCart.jsp</title>
<style>
table, td, th{
}
th{
background-color: lightblue;
}
table{
text-align: center;
width: 800px;
margin: 0 auto;
border-top: 5px solid black;
border-bottom: 5px solid black;
}
img{
width: 100px;
height: 100px;
}
#text{
text-align: center;
font: 100px;
}
</style>
</head>
<body>
<div id="text">
<h2> 장바구니 </h2>
</div>
<table>
<tr>
<th>상품번호</th>
<th>상품명</th>
<th>이미지</th>
<th>수량</th>
<th>가격</th>
<th>할인가격</th>
</tr>
<%
// session에서 cart 속성 가져오기
Object obj = session.getAttribute("cart");
if(obj == null) {
// ArrayList 생성
ArrayList<Integer> cart = new ArrayList<Integer>();
// 세션의 속성으로 지정
session.setAttribute("cart", cart);
// 세션에서 속성 가져오기
obj = session.getAttribute("cart");
}
// ArrayList로 형변환
ArrayList<Integer> cart = (ArrayList<Integer>)obj;
// 1개씩 꺼내서 상품과 수량을 집계
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(Integer it : cart){
//n번 상품이 존재한다면
if(map.containsKey(it)) {
/* // 현재 상품의 갯수 구하기
int cnt = map.get(it);
// 상품 갯수에 1 추가하기
cnt++;
// 그리고 다시 맵에 넣기 => 키는 중복되지 않아 마지막 값만 저장
map.put(it, cnt); */
map.put(it, map.get(it)+1);
} else { // n번 상품이 존재하지 않는다면
map.put(it, 1);
}
/* System.out.println("map : "+map); */
}
// 화면에 표 형태로 출력
// 맵에서 상품의 번호만 가져오기
Set key = map.keySet(); // 상품 번호만 set 타입으로 리턴
// ex) 110, 121 물건의 가격, 이미지, 할인율
ProductDAO dao = new ProductDAO();
ArrayList<ProductVO> item = dao.getData(key);
int total = 0;
for(ProductVO vo : item) {
int cnt = map.get(vo.getPno());
total += (int)(Math.round(vo.getPrice()*(1-vo.getDcratio()*0.01)*cnt));
%>
<tr>
<td><%=vo.getPno() %></td>
<td><%=vo.getPname() %></td>
<td><img src="<%=vo.getImgfile()%>" alt="" /></td>
<td><%=cnt %></td>
<td><%=vo.getPrice() %>원</td>
<td><%= Math.round(vo.getPrice()*(1-vo.getDcratio()*0.01)) %>원</td>
</tr>
<%
}
// 표 형태로
// 상품번호 상품명 이미지 (작게) 수량 가격 할인가격
// 110 티셔츠 ~~~ 2 5000 9000
// 121 신발 ~~~ 1 4000 3600
%>
<tr>
<!-- colspan: 몇 칸 정도 차지하는지 -->
<td colspan="5">합계</td>
<td><%=total %>원</td>
</tr>
</table>
</body>
</html>
|
cs |
++ hashmap 복습 : [TestMain.java]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
package day06;
import java.util.HashMap;
public class TestMain {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
// 중국집..
map.put("짜장면", 2);
map.put("짜장면", 1);
map.put("짬뽕", 1);
// value는 중복될 수 있지만, key는 중복되지 않음
System.out.println("map : "+map);
// 키로 value를 찾기
int cnt = map.get("짬뽕");
System.out.println("짬뽕 갯수 : "+cnt);
// 키 중에서 탕수육이 있는지 여부를 확인
boolean isOK = map.containsKey("탕수육");
System.out.println("탕수육있니? : "+ isOK);
// value 값이 존재하는지 여부를 확인
boolean isWho = map.containsValue(1);
System.out.println("혼자 주문한 사람이 있니? : " + isWho);
}
}
|
cs |
< 우편번호 찾기 >
* 다음 주소록 활용
- [addrss1.jsp] : http://postcode.map.daum.net/guide
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>address1.jsp</title>
<script src="//t1.daumcdn.net/mapjsapi/bundle/postcode/prod/postcode.v2.js"></script>
<script type="text/javascript">
window.onload=function(){
var btn = document.getElementById("btn");
btn.onclick = openKakaoPostCode;
}
function openKakaoPostCode(){
console.log("openKakaoPostCode 함수 호출중");
new daum.Postcode({
oncomplete: function(data){
// 팝업에서 검색 결과 항목을 클릭했을 때
// 실행할 코드를 작성하는 부분
// console.log("팝업검색 버튼 누름");
console.dir(data);
document.getElementById("post1").value = data.zonecode;
document.getElementById("addrs").value = data.address;
document.getElementById("addrs2").value = data.jibunAddress;
}
}).open();
}
</script>
</head>
<body>
<h1>우편번호</h1>
<!-- API(Application Programming Interface) -->
<input type="text" name="" id="post1" />
<input type="button" value="우편번호찾기" id="btn" /> <br />
도로명 : <input type="text" name="" id="addrs" size="100" /> <br />
지번 : <input type="text" name="" id="addrs2" size="70" /> <br />
</body>
</html>
|
cs |
'web' 카테고리의 다른 글
[jsp] 게시판 만들기 (게시물 작성/수정/게시물 리스트) (0) | 2023.04.30 |
---|---|
[jsp] 글 작성 게시물 만들기 (0) | 2023.04.30 |
[jsp] 네이버 메인 페이지 만들기(토픽 별 페이지, 로그인 화면) (0) | 2023.04.30 |
[jsp] cookie 처리(생성, 읽기, 삭제) + 자바스크립트로! (0) | 2023.04.30 |
[jsp] jsp 파일 불러오기 - include & action tag (0) | 2023.04.30 |