19.05.20 jsp 쇼핑몰 차량 구매하기 예약 및 결과 (동영상 68강)

Back-End/JSP 2019. 5. 20. 15:34

쇼핑몰 차량 구매하기 예약 및 결과



CarReserveResult.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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
<%@page import="db.CarListBean"%>
<%@page import="db.RentcarDAO"%>
<%@page import="java.text.SimpleDateFormat"%>
<%@page import="java.util.Date"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
    <!-- 한글이 넘어올수도 있기 때문에 문자셋설정을 다시한다. -->
 
    <%
        request.setCharacterEncoding("euc-kr");
    %>
    <!-- 한번에 빈클래스에 있는 값들을 받아야되서 useBean 사용 -->
    <jsp:useBean id="rbean" class="db.CarReserveBean">
        <jsp:setProperty name="rbean" property="*" />
    </jsp:useBean>
 
    <%
        //로그인한 아이디가 페이지가 변경되어도 유지가 되어야하기 때문에 세션으로 받는다.
        //받는 아이디는 오브젝트 타입이기 때문에 String 타입으로 타입변환을 시켜준다.
        String id = (String) session.getAttribute("id");
 
        //null값과 비교할시에는 GUEST값이 나와버리므로 
        //null 대신에 GUEST와 비교한다.
        //비교한후에 참이면 (로그인이 안되었으면) 로그인페이지로 이동하게함
        if (id == null) {
    %>
 
    <script>
        //예약할시에 로그인이 안되어있을경우 출력되는 메시지
        alert("로그인후 예약이 가능합니다.");
        //로그인이 안되어있을경우 로그인 페이지로 이동
        location.href = 'RentcarMain.jsp?center=MemberLogin.jsp';
    </script>
 
    <%
        }
        //날짜 비교 (현재 날짜보다 앞에 날짜는 선택 못하게 하기.. )
        Date d1 = new Date();
        Date d2 = new Date();
        //날짜를 2016-4-4 로 포맷해주는 클래스 선언, month은 대문자 M을 사용
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
 
        //d1은 yyyy-MM-dd 형식으로 변경된다.
        d1 = sdf.parse(rbean.getRday());
        //d2는 yyyy-MM-dd 형식으로 변경된다.
        d2 = sdf.parse(sdf.format(d2));
 
        //날짜 비교 메소드를 사용가능 date 클래스 사용
 
        int compare = d1.compareTo(d2);
        //예약하려는 날짜보다 현재 날짜가 크다면 -1을 반환
        //예약하려는 날짜와 현재 날짜가 같다면 0을 반환
        //예약하려는 날짜가 더 크다면 1을 리턴함
 
        if (compare < 0) {
            //오늘보다 이전 날짜 선택시 예약이 안되게끔 해야함
    %>
 
    <script>
        alert("현재 시스템 날짜보다 이전 날짜는 선택할 수 없음");
        history.go(-1);//이전 단계로 이동하시오.
    </script>
 
    <%
        }
 
        //결과적으로 아무런 문제가 없다면 데이터 저장후 결과 페이지로 이동하기
        //아이디값이 빈 클래스에 없고, 세션에 저장시켰기 때문
        //id는 null값이 들어갈수 있으므로 변수이름을 id1 으로 한다.
        String id1 = (String) session.getAttribute("id");
        rbean.setId(id1);
 
        //데이터베이스에 빈클래스를 저장함
        RentcarDAO rdao = new RentcarDAO();
        rdao.setReserveCar(rbean);
 
        //차량정보 얻어오기 CarReserveBean에는 차량 사진이 저장되어 있지 않기때문에 다른곳에서 얻어와야 한다.
        CarListBean cbean = rdao.getOneCar(rbean.getNo());
 
        //차량 총 금액, 금액 * 차량 대수 * 빌리는 날짜
        int totalcar = cbean.getPrice() * rbean.getQty() * rbean.getDday();
        //옵션 금액
        int usein = 0;
        if (rbean.getUsein() == 1)
            usein = 10000;
 
        int usewifi = 0;
        if (rbean.getUsewifi() == 1)
            usewifi = 10000;
 
        int useseat = 0;
        if (rbean.getUseseat() == 1)
            useseat = 10000;
 
        //옵션의 총금액 (보험 등등등)
        int totaloption = (rbean.getQty() * rbean.getDday()) * (usein + usewifi + useseat);
    %>
    <center>
        <table width="1000">
            <tr height="100">
                <td align="center"><font size="6" color="gray"> 차량 예약 완료
                        화면 </font></td>
            </tr>
 
            <tr>
                <td align="center"><img alt="" src="img<%=cbean.getImg()%>"
                    width="470"></td>
            </tr>
 
            <tr height="50">
                <td align="center"><font size="5" color="red"> 차량 총예약 금액
                        <%=totalcar%>
                </font></td>
            </tr>
 
            <tr height="50">
                <td align="center"><font size="5" color="red"> 차량 총옵션 금액
                        <%=totaloption%>
                </font></td>
            </tr>
 
            <tr height="50">
                <td align="center"><font size="5" color="red"> 차량 총 금액 <%=totaloption + totalcar%>
                </font></td>
            </tr>
 
        </table>
    </center>
</body>
</html>
cs



CarReserveBean.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
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
package db;
 
public class CarReserveBean {
 
    private int reserveno;
    private String id;
    private int no;
    private int qty;
    private int dday; // 대여기간
    private String rday; // 대여일은 date타입으로 받았지만 넘겨줄때 String타입으로 변하므로 String타입으로 해야함
    private int usein;
    private int usewifi;
    private int useseat;
    private int usenavi;
 
    public int getReserveno() {
        return reserveno;
    }
 
    public void setReserveno(int reserveno) {
        this.reserveno = reserveno;
    }
 
    public String getId() {
        return id;
    }
 
    public void setId(String id) {
        this.id = id;
    }
 
    public int getNo() {
        return no;
    }
 
    public void setNo(int no) {
        this.no = no;
    }
 
    public int getQty() {
        return qty;
    }
 
    public void setQty(int qty) {
        this.qty = qty;
    }
 
    public int getDday() {
        return dday;
    }
 
    public void setDday(int dday) {
        this.dday = dday;
    }
 
    public String getRday() {
        return rday;
    }
 
    public void setRday(String rday) {
        this.rday = rday;
    }
 
    public int getUsein() {
        return usein;
    }
 
    public void setUsein(int usein) {
        this.usein = usein;
    }
 
    public int getUsewifi() {
        return usewifi;
    }
 
    public void setUsewifi(int usewifi) {
        this.usewifi = usewifi;
    }
 
    public int getUseseat() {
        return useseat;
    }
 
    public void setUseseat(int useseat) {
        this.useseat = useseat;
    }
 
    public int getUsenavi() {
        return usenavi;
    }
 
    public void setUsenavi(int usenavi) {
        this.usenavi = usenavi;
    }
 
}
 
cs





:

19.05.19 jsp 쇼핑몰 차량 날짜 처리 (동영상 67강)

Back-End/JSP 2019. 5. 19. 22:19

차량 구매할때 날짜 처리 (현재 날짜보다 지난 날짜는 선택 못하게 하기)

 

 

DB테이블 파일

New 1.sql

 

 

데이터베이스 테이블 생성 (차량 옵션 값이 저장되는 테이블)

 

 

CarReserveBean.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
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
package db;
 
public class CarReserveBean {
 
    private int reserveno;
    private String id;
    private int no;
    private int qty;
    private int dday; // 대여기간
    private String rday; // 대여일은 date타입으로 받았지만 넘겨줄때 String타입으로 변하므로 String타입으로 해야함
    private int usein;
    private int usewifi;
    private int useseat;
    private int usenavi;
 
    public int getReserveno() {
        return reserveno;
    }
 
    public void setReserveno(int reserveno) {
        this.reserveno = reserveno;
    }
 
    public String getId() {
        return id;
    }
 
    public void setId(String id) {
        this.id = id;
    }
 
    public int getNo() {
        return no;
    }
 
    public void setNo(int no) {
        this.no = no;
    }
 
    public int getQty() {
        return qty;
    }
 
    public void setQty(int qty) {
        this.qty = qty;
    }
 
    public int getDday() {
        return dday;
    }
 
    public void setDday(int dday) {
        this.dday = dday;
    }
 
    public String getRday() {
        return rday;
    }
 
    public void setRday(String rday) {
        this.rday = rday;
    }
 
    public int getUsein() {
        return usein;
    }
 
    public void setUsein(int usein) {
        this.usein = usein;
    }
 
    public int getUsewifi() {
        return usewifi;
    }
 
    public void setUsewifi(int usewifi) {
        this.usewifi = usewifi;
    }
 
    public int getUseseat() {
        return useseat;
    }
 
    public void setUseseat(int useseat) {
        this.useseat = useseat;
    }
 
    public int getUsenavi() {
        return usenavi;
    }
 
    public void setUsenavi(int usenavi) {
        this.usenavi = usenavi;
    }
 
}
 
cs

 

 

CarReserveResult.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
<%@page import="java.text.SimpleDateFormat"%>
<%@page import="java.util.Date"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
    <!-- 한글이 넘어올수도 있기 때문에 문자셋설정을 다시한다. -->
 
    <%
        request.setCharacterEncoding("euc-kr");
    %>
    <!-- 한번에 빈클래스에 있는 값들을 받아야되서 useBean 사용 -->
    <jsp:useBean id="rbean" class="db.CarReserveBean">
        <jsp:setProperty name="rbean" property="*" />
    </jsp:useBean>
 
    <%
        //로그인한 아이디가 페이지가 변경되어도 유지가 되어야하기 때문에 세션으로 받는다.
        //받는 아이디는 오브젝트 타입이기 때문에 String 타입으로 타입변환을 시켜준다.
        String id = (String) session.getAttribute("id");
 
        //null값과 비교할시에는 GUEST값이 나와버리므로 
        //null 대신에 GUEST와 비교한다.
        //비교한후에 참이면 (로그인이 안되었으면) 로그인페이지로 이동하게함
        if (id == null) {
    %>
 
    <script>
        //예약할시에 로그인이 안되어있을경우 출력되는 메시지
        alert("로그인후 예약이 가능합니다.");
        //로그인이 안되어있을경우 로그인 페이지로 이동
        location.href = 'RentcarMain.jsp?center=MemberLogin.jsp';
    </script>
 
    <%
        }
        //날짜 비교 (현재 날짜보다 앞에 날짜는 선택 못하게 하기.. )
        Date d1 = new Date();
        Date d2 = new Date();
        //날짜를 2016-4-4 로 포맷해주는 클래스 선언, month은 대문자 M을 사용
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
 
        //d1은 yyyy-MM-dd 형식으로 변경된다.
        d1 = sdf.parse(rbean.getRday());
        //d2는 yyyy-MM-dd 형식으로 변경된다.
        d2 = sdf.parse(sdf.format(d2));
 
        //날짜 비교 메소드를 사용가능 date 클래스 사용
 
        int compare = d1.compareTo(d2);
        //예약하려는 날짜보다 현재 날짜가 크다면 -1을 반환
        //예약하려는 날짜와 현재 날짜가 같다면 0을 반환
        //예약하려는 날짜가 더 크다면 1을 리턴함
 
        if (compare < 0) {
            //오늘보다 이전 날짜 선택시 예약이 안되게끔 해야함
    %>
 
    <script>
        alert("현재 시스템 날짜보다 이전 날짜는 선택할 수 없음");
        history.go(-1);//이전 단계로 이동하시오.
    </script>
 
    <%
        }
    %>
 
 
</body>
</html>
cs

 

 

 

 

:

19.05.19 jsp 쇼핑몰 로그인 (동영상 66강)

Back-End/JSP 2019. 5. 19. 20:30

쇼핑몰 로그인 페이지 구현

 

 

MemberLogin.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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
    <!-- 로그인 페이지 -->
    <!-- 아이디랑 패스워드만 받게할 예정 -->
    <form action="MemberLoginProc.jsp" method="post">
        <table width="300" border="1" bordercolor="gray">
            <tr height="100">
                <td align="center" colspan="2"><font size="6" color="gray">로그인
                </font></td>
            </tr>
            <tr height="40">
                <td width="120" align="center">아이디</td>
                <td width="180"><input type="text" name="id" size="15"></td>
            </tr>
 
            <tr height="40">
                <td width="120" align="center">패스워드</td>
                <td width="180"><input type="password" name="pass" size="15"></td>
            </tr>
 
            <tr height="40">
                <td align="center" colspan="2"><input type="submit" value="로그인"></td>
            </tr>
 
 
 
 
        </table>
    </form>
</body>
</html>
cs

 

 

MemberLoginProc.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
<%@page import="db.RentcarDAO"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
 
    <% 
    //로그인 처리 페이지, 한글깨짐 방지
 
    String id = request.getParameter("id");
    String pass = request.getParameter("pass");
    //회원 아이디와 패스워드가 일치하는지 비교한다.
    RentcarDAO rdao = new RentcarDAO();
    
    //해당 회원이 있는지 여부를 숫자로 반환받는다.
    int result = rdao.getMember(id,pass);
    
    if(result==0)
    {
%>
 
    <script>//예약할시에 로그인이 안되어있을경우 출력되는 메시지
        alert("회원 아이디 또는 패스워드가 틀립니다.");
    //로그인이 안되어있을경우 로그인 페이지로 이동
        location.href='RentcarMain.jsp?center=MemberLogin.jsp';
    </script>
 
    <%
    }else
    {
        //로그인 처리가 되었다면 세션에 담아야 화면이 넘어갈때 유지된다.
        session.setAttribute("id", id);
        response.sendRedirect("RentcarMain.jsp");
    }
    
    
 
%>
 
 
</body>
</html>
cs

 

 

Top.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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
 
    <!-- 세션을 이용한 로그인 처리 -->
    <!-- 세션으로 받아온 값은 오브젝트 타입이기 때문에 String 타입으로 컨버팅 한다. -->
 
    <%
        String id = (String) session.getAttribute("id");
 
        //로그인이 되어있지 않다면 id에 "GUEST"값을 준다
        if (id == null) {
            id = "GUEST";
        }
    %>
 
    <table width="1000" bordercolor="white">
        <tr height="70">
            <td colspan="4"><a href="RentcarMain.jsp"
                style="text-decoration: none"> <!-- 이미지를 불러오기위한 태그 작성 --> <img
                    alt="" src="img/RENT.jpg" height="150" width="250">
            </a></td>
            <td align="center" width="200"><%=id%> 님 <%
                if(id.equals("GUEST")){ %>
                <button
                    onclick="location.href='RentcarMain.jsp?center=MemberLogin.jsp'">
                    로그인</button> <%
                }else{%>
                <button onclick="location.href='MemberLogout.jsp'">로그아웃</button> <% 
                }
                
            %></td>
        </tr>
        <!-- 글자를 누르면 화면이 넘어갈수 있도록 a태그를 걸어줌 -->
        <tr height="50">
            <td align="center" width="200" bgcolor="pink"><font
                color="white" size="5"> <a
                    href="RentcarMain.jsp?center=CarReserveMain.jsp"
                    style="text-decoration: none"> 예 약 하 기 </a></font></td>
 
            <td align="center" width="200" bgcolor="pink">
                <!-- 글자를 누르면 화면이 넘어갈수 있도록 a태그를 걸어줌 --> <font color="white" size="5"><a
                    href="#" style="text-decoration: none"> 예 약 확 인</a></font>
            </td>
 
            <td align="center" width="200" bgcolor="pink">
                <!-- 글자를 누르면 화면이 넘어갈수 있도록 a태그를 걸어줌 --> <font color="white" size="5"><a
                    href="#" style="text-decoration: none"> 자 유 게 시 판 </a></font>
            </td>
 
            <td align="center" width="200" bgcolor="pink">
                <!-- 글자를 누르면 화면이 넘어갈수 있도록 a태그를 걸어줌 --> <font color="white" size="5"><a
                    href="#" style="text-decoration: none"> 이 벤 트 </a></font>
            </td>
 
            <td align="center" width="200" bgcolor="pink">
                <!-- 글자를 누르면 화면이 넘어갈수 있도록 a태그를 걸어줌 --> <font color="white" size="5"><a
                    href="#" style="text-decoration: none"> 고 객 센 터 </a></font>
            </td>
        </tr>
 
    </table>
</body>
</html>
 
cs

 

 

RentcarDAO.java (DB연결)

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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
package db;
 
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Vector;
 
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
 
public class RentcarDAO {
 
    Connection con;
    PreparedStatement pstmt;
    ResultSet rs;
 
    // 커넥션풀을 이용한 데이터베이스 연결
 
    public void getcon() {
 
        // DB에 접속할때는 예외처리를 실시해야됨
        try {
 
            Context initctx = new InitialContext(); // 외부서버로 부터 데이터를 읽어들이는것이기 때문에 드라이버가 없을수 있어
            Context envctx = (Context) initctx.lookup("java:comp/env"); // 자바를 읽어들일수 있는 환경에서 사용 //예외처리를 해준다.
            DataSource ds = (DataSource) envctx.lookup("jdbc/pool");
            con = ds.getConnection();
            // 데이터소스에 username, url, password를 집어넣는다. 그렇게 하면 데이터소스가 커넥션을 얻어 온다.
            // jdbc/pool에 있는 데이터소스를 사용할수 있다.
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
 
        }
    }
 
    // 최신순 3대의 자동차를 리턴하는 메소드
    public Vector<CarListBean> getSelectCar() {
        // 리턴타입을 설정
        Vector<CarListBean> v = new Vector<>();
        getcon(); // 커넥션이 연결되어야 쿼리를 실행 가능
 
        try {
 
            String sql = "select * from rentcar order by no desc ";
            pstmt = con.prepareStatement(sql);
            // 쿼리 실행후 실행결과 Result리턴함
            rs = pstmt.executeQuery();
            int count = 0;
            while (rs.next())// 결과값이 끝날때까지만 실행
            {
                CarListBean bean = new CarListBean();
                bean.setNo(rs.getInt(1));
                bean.setName(rs.getString(2));
                bean.setCategory(rs.getInt(3));
                bean.setPrice(rs.getInt(4));
                bean.setUsepeople(rs.getInt(5));
                bean.setCompany(rs.getString(6));
                bean.setImg(rs.getString(7));
                bean.setInfo(rs.getString(8));
                // 벡터에 빈 클래스를 저장
                v.add(bean);
                count++;
                // 3개만 저장이 되야하기 때문..
                if (count > 3)
                    break// 반복문을 빠져나가시오.
 
            }
            con.close();
        } catch (Exception e) {// 내림차순으로 검색하는 쿼리문 작성
            e.printStackTrace();
        }
        return v;
 
    }
 
    // 카테고리별 자동차 리스트를 저장하는 메소드
    // 벡터로 받았으니 벡터로 리턴함..
    public Vector<CarListBean> getCategoryCar(int cate)
 
    {
        // 리턴타입이 벡터 객체이기 때문에 벡터 객체를 생성한다.
        Vector<CarListBean> v = new Vector<>();
 
        // 데이터를 저장할 빈 클래스 선언
        CarListBean bean = null;
 
        getcon();
 
        try {
            String sql = "select * from rentcar where category=?";
            pstmt = con.prepareStatement(sql);
 
            // ?에 값을 넣는다.
            pstmt.setInt(1, cate);
            // 결과를 리턴
            rs = pstmt.executeQuery();
            // 반복문을 돌려서 데이터를 저장
 
            while (rs.next()) { // 데이터를 저장할 빈 클래스 생성
                bean = new CarListBean();
                bean.setNo(rs.getInt(1));
                bean.setName(rs.getString(2));
                bean.setCategory(rs.getInt(3));
                bean.setPrice(rs.getInt(4));
                bean.setUsepeople(rs.getInt(5));
                bean.setCompany(rs.getString(6));
                bean.setImg(rs.getString(7));
                bean.setInfo(rs.getString(8));
                // 벡터에 빈 클래스를 저장
                v.add(bean);
 
            }
 
            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        return v;
 
    }
 
    // 모든 차량을 검색하는 메소드
    public Vector<CarListBean> getAllCar() {
 
        Vector<CarListBean> v = new Vector<>();
        // 데이터를 저장할 빈클래스 선언
        CarListBean bean = null;
 
        getcon();
 
        try {
            String sql = "select * from rentcar";
            pstmt = con.prepareStatement(sql);
            rs = pstmt.executeQuery();
            // 반복문을 돌리면서 데이터를 저장함
 
            while (rs.next()) {// 데이터를 저장할 빈클래스 생성
                bean = new CarListBean();
                bean.setNo(rs.getInt(1));
                bean.setName(rs.getString(2));
                bean.setCategory(rs.getInt(3));
                bean.setPrice(rs.getInt(4));
                bean.setUsepeople(rs.getInt(5));
                bean.setCompany(rs.getString(6));
                bean.setImg(rs.getString(7));
                bean.setInfo(rs.getString(8));
                // 벡터에 빈 클래스를 저장
                v.add(bean);
 
            }
 
            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return v;
 
    }
 
    // 하나의 자동차 정보를 리턴하는 메소드
    public CarListBean getOneCar(int no) {
 
        // 리턴타입을 선언한다. 객체를 생성해서 그 객체에 값을 넣은후 리턴해야하기 때문
        CarListBean bean = new CarListBean();
 
        getcon();
 
        try {
            String sql = "select * from rentcar where no=?";
            pstmt = con.prepareStatement(sql);
            // sql문에 ?표가 들어가 있으면 초기 인덱스 값을 할당해주어야 한다.
            pstmt.setInt(1, no);
            rs = pstmt.executeQuery();
 
            if (rs.next()) {
                bean.setNo(rs.getInt(1));
                bean.setName(rs.getString(2));
                bean.setCategory(rs.getInt(3));
                bean.setPrice(rs.getInt(4));
                bean.setUsepeople(rs.getInt(5));
                bean.setCompany(rs.getString(6));
                bean.setImg(rs.getString(7));
                bean.setInfo(rs.getString(8));
 
            }
 
            con.close();
 
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bean;
 
    }
 
    // 회원 정보가 있는지를 비교한다.
    public int getMember(String id, String pass) {
        int result = 0// 0이면 회원이 없다고 가정
        getcon();
 
        try { //아이디와 패스워드가 모두 있는 회원의 숫자를 반환하는 sql문
            String sql = "select count(*) from member where id=? and pass1=?";
            pstmt = con.prepareStatement(sql);
            // sql문에 ?표가 들어가 있으면 초기 인덱스 값을 할당해주어야 한다.
 
            pstmt.setString(1, id);
            pstmt.setString(2, pass);
 
            rs = pstmt.executeQuery();
 
            if (rs.next()) {
                result = rs.getInt(1); // 0또는 1이 저장된다. 0이면 회원이 없는거고, 1이면 있는것
            }
 
            con.close();
 
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
 
    }
 
}
 
cs

 

 

 

:

19.05.19 jsp 쇼핑몰 차량 구매하기 (동영상 64강~65강)

Back-End/JSP 2019. 5. 19. 17:39

쇼핑몰 차량 구매하기 기능 구현

 

 

Top.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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
 
    <!-- 세션을 이용한 로그인 처리 -->
    <!-- 세션으로 받아온 값은 오브젝트 타입이기 때문에 String 타입으로 컨버팅 한다. -->
 
    <%
        String id = (String) session.getAttribute("id");
 
        //로그인이 되어있지 않다면 id에 "GUEST"값을 준다
        if (id == null) {
            id = "GUEST";
        }
    %>
 
    <table width="1000" bordercolor="white">
        <tr height="70">
            <td colspan="4"><a href="RentcarMain.jsp"
                style="text-decoration: none"> <!-- 이미지를 불러오기위한 태그 작성 --> <img
                    alt="" src="img/RENT.jpg" height="150" width="250">
            </a></td>
            <td align="center" width="200"><%=id%> 님 <%
                if(id.equals("GUEST")){ %>
                <button onclick="RentcarMain.jsp?center=MemberLogin.jsp">
                    로그인</button> <%
                }
            %></td>
        </tr>
        <!-- 글자를 누르면 화면이 넘어갈수 있도록 a태그를 걸어줌 -->
        <tr height="50">
            <td align="center" width="200" bgcolor="pink"><font
                color="white" size="5"> <a
                    href="RentcarMain.jsp?center=CarReserveMain.jsp"
                    style="text-decoration: none"> 예 약 하 기 </a></font></td>
 
            <td align="center" width="200" bgcolor="pink">
                <!-- 글자를 누르면 화면이 넘어갈수 있도록 a태그를 걸어줌 --> <font color="white" size="5"><a
                    href="#" style="text-decoration: none"> 예 약 확 인</a></font>
            </td>
 
            <td align="center" width="200" bgcolor="pink">
                <!-- 글자를 누르면 화면이 넘어갈수 있도록 a태그를 걸어줌 --> <font color="white" size="5"><a
                    href="#" style="text-decoration: none"> 자 유 게 시 판 </a></font>
            </td>
 
            <td align="center" width="200" bgcolor="pink">
                <!-- 글자를 누르면 화면이 넘어갈수 있도록 a태그를 걸어줌 --> <font color="white" size="5"><a
                    href="#" style="text-decoration: none"> 이 벤 트 </a></font>
            </td>
 
            <td align="center" width="200" bgcolor="pink">
                <!-- 글자를 누르면 화면이 넘어갈수 있도록 a태그를 걸어줌 --> <font color="white" size="5"><a
                    href="#" style="text-decoration: none"> 고 객 센 터 </a></font>
            </td>
        </tr>
 
    </table>
</body>
</html>
 
cs

 

 

CarReserveResult.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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
    <!-- 한글이 넘어올수도 있기 때문에 문자셋설정을 다시한다. -->
 
    <% 
    request.setCharacterEncoding("euc-kr");
%>
    <!-- 한번에 빈클래스에 있는 값들을 받아야되서 useBean 사용 -->
    <jsp:useBean id="rbean" class="db.CarReserveBean">
        <jsp:setProperty name="rbean" property="*" />
    </jsp:useBean>
 
    <% 
    //로그인한 아이디가 페이지가 변경되어도 유지가 되어야하기 때문에 세션으로 받는다.
    //받는 아이디는 오브젝트 타입이기 때문에 String 타입으로 타입변환을 시켜준다.
    String id = (String)session.getAttribute("id");
    
 
    //null값과 비교할시에는 GUEST값이 나와버리므로 
    //null 대신에 GUEST와 비교한다.
    //비교한후에 참이면 (로그인이 안되었으면) 로그인페이지로 이동하게함
    if(id==null)
    {
%>
    <script>//예약할시에 로그인이 안되어있을경우 출력되는 메시지
        alert("로그인후 예약이 가능합니다.");
    </script>
    <%
        response.sendRedirect("RentcarMain.jsp?center=MemberLogin.jsp");
    }
 
%>
 
 
</body>
</html>
cs

 

 

CarOptionSelect.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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<html>
<body>
    <% 
    int no = Integer.parseInt(request.getParameter("no"));
    
    //차량 수량
    int qty = Integer.parseInt(request.getParameter("qty"));
    //이미지를 가져옴
    String img = request.getParameter("img");
%>
    <div style="text-align: center;">
        <form action="RentcarMain.jsp?center=CarReserveResult.jsp"
            method="post">
            <table width="1000">
                <tr height="100">
                    <td align="center" colspan="3"><font size="6" color="gray">
                            옵션 선택 </font></td>
                </tr>
                <tr>
                    <!-- colspan은 가로셀끼리 병합하는 것이고, rowspan은 세로 셀끼리 병합하는 것 -->
                    <!-- 차량 사진 옆에 정보들이 떠야하기때문에 세로병합인 rowspan을 사용 -->
                    <td rowspan="7" width="500" align="center"><img alt=""
                        src="img/<%=img %>" width="450"></td>
                    <td width="250" align="center">대여기간</td>
                    <td width="250" align="center"><select name="dday">
                            <option value="1">1일</option>
                            <option value="2">2일</option>
                            <option value="3">3일</option>
                            <option value="4">4일</option>
                            <option value="5">5일</option>
                            <option value="6">6일</option>
                            <option value="7">7일</option>
                    </select></td>
                </tr>
                <tr>
                    <td width="250" align="center">대여일</td>
                    <td width="250" align="center"><input type="date" name="rday"
                        size="15"></td>
                <tr>
                    <td width="250" align="center">보험적용</td>
                    <td width="250" align="center"><select name="usein">
                            <option value="1">적용 (1일 1만원)</option>
                            <option value="2">미적용</option>
                    </select></td>
                </tr>
 
                <tr>
                    <td width="250" align="center">wifi 적용</td>
                    <td width="250" align="center"><select name="usewifi">
                            <option value="1">적용 (1일 1만원)</option>
                            <option value="2">미적용</option>
                    </select></td>
                </tr>
 
                <tr>
                    <td width="250" align="center">네비게이션 적용</td>
                    <td width="250" align="center"><select name="usenavi">
                            <option value="1">적용 (무료)</option>
                            <option value="2">미적용</option>
                    </select></td>
                </tr>
 
 
                <tr>
                    <td width="250" align="center">베이비시트 적용</td>
                    <td width="250" align="center"><select name="useseat">
                            <option value="1">적용 (1일 1만원)</option>
                            <option value="2">미적용</option>
                    </select></td>
                </tr>
 
                <tr>
                    <td align="center" colspan="2"><input type="hidden" name="no"
                        value="<%=no %>"> <input type="hidden" name="qty"
                        value="<%=qty %>"> <input type="submit" value="차량예약하기"></td>
                </tr>
 
            </table>
        </form>
    </div>
</body>
</html>
cs

 

 

CarReserveBean.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
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
package db;
 
 
public class CarReserveBean {
    
    private int no;
    private int qty;
    private int dday; //대여기간
    private String rday; //대여일은 date타입으로 받았지만 넘겨줄때 String타입으로 변하므로 String타입으로 해야함
    private int usein;
    private int usewifi;
    private int usenavi;
    private int useseat;
    
    
    public int getNo() {
        return no;
    }
    public void setNo(int no) {
        this.no = no;
    }
    public int getQty() {
        return qty;
    }
    public void setQty(int qty) {
        this.qty = qty;
    }
    public int getDday() {
        return dday;
    }
    public void setDday(int dday) {
        this.dday = dday;
    }
    public String getRday() {
        return rday;
    }
    public void setRday(String rday) {
        this.rday = rday;
    }
    public int getUsein() {
        return usein;
    }
    public void setUsein(int usein) {
        this.usein = usein;
    }
    public int getUsewifi() {
        return usewifi;
    }
    public void setUsewifi(int usewifi) {
        this.usewifi = usewifi;
    }
    public int getUsenavi() {
        return usenavi;
    }
    public void setUsenavi(int usenavi) {
        this.usenavi = usenavi;
    }
    public int getUseseat() {
        return useseat;
    }
    public void setUseseat(int useseat) {
        this.useseat = useseat;
    }
    
    
    
    
    
 
}
 
cs

 

:

HTML <input type> 관련

Back-End/Problems 2019. 5. 19. 15:25

<input type>를 사용할때 HTML 버전에 따라서 사용할수 있는 타입이 추가가 된다.

당연히 HTML4버전에서 5버전에 추가된 타입들을 넣으면 실행되지 않는다.

 

 

 

또한, 이클립스에서 실행하면 제대로 나오지않고, 브라우저에서만 나오는 타입도 있다.

 

 

 

이클립스에서 실행

 

 

 

 

크롬 브라우저에서 실행

 

:

인터페이스 관련 자료구조

Algorithm/자료구조와 알고리즘 2019. 5. 19. 11:39

-자바 interface-

 

자바 interface는 메서드 집합을 의미.

이 interface를 구현하는 클래스는 이러한 메서드를 제공해야 합니다.

예를 들어,  java.lang 패키지에 정의된 Comparable interface 의 소스코드는 다음과 같다.

 

 

  public interface Comparable<T>{

  public int compareTo(T o);

  }

 

 

이러한 interface는 타입 파라미터인 T를 사용하여 Comparable라는 제네릭 타입을 정의합니다.

interface를 구현하려면 클래스는 T 타입을 명시해야 하고, T 타입의 객체를 인자로 받고 int를 반환하는 compareTo() 메서드를 제공해야 합니다.

 

예를 들어,  java.lang.Integer 클래스의 소스 코드는 다음과 같습니다.

 

 

  public final class Integer extends Number implements Comparable<Integer>    {

  public int compareTo(Integer antherInteger) {

  int thisVal = this.value;

  int anogherVal = anotherInteger.value;

  return (thisVal<anotherVal ? -1 : (thisVal == anotherVal ? 0 : 1 ));

  }

  //다른 메서드 생략함

  }

 

 

 

 

-제네릭-

 

자바에서 제네릭(Generic)이란 데이터의 타입(Data Type)을 일반화한다(Generalize)는 것을 의미한다.

제네릭은 클래스나 메소드에서 사용할 내부 데이터 타입을 컴파일 시에 미리 지정하는 방법이다.

이렇게 컴파일 시에 미리 타입 검사(Type Check)를 수행하면 다음과 같은 장점을 가진다.

1. 클래스나 메소드 내부에서 사용되는 객체의 타입 안정성을 높일 수 있다.

2. 반환값에 대한 타입 변환 및 타입 검사에 들어가는 노력을 줄일 수 있다.

JDK 1.5 이전에서는 여러 타입을 사용하는 대부분의 클래스나 메소드에서 인수나 반환값으로 Object 타입을 사용했다.

하지만 이 경우에는 반환된 Object 객체를 다시 원하는 타입으로 타입 변환해야 하며, 이때 오류가 발생할 가능성도 존재한다.

JDK 1.5부터 도입된 제네릭을 사용하면 컴파일 시에 미리 타입이 정해지므로, 타입 검사나 타입 변환과 같은 번거로운 작업을 생략할 수 있다.

 

 

 

-List interface-

 

JCF는 List라는 interface를 정의하고 ArrayList와 LinkedList라는 두 구현 클래스를 제공합니다.

interface는 List가 된다는 의미가 무엇인지를 정의합니다.

이 interface를 구현하는 클래스는 add, get, remove와 약 20가지 메서드를 포함한 특정 메서드 집합을 제공해야 합니다.

 

ArrayList와 LinkedList 클래스는 이러한 메서드를 제공하므로 상호교환할 수 있습니다.

List로 동작하는 메서드는 ArrayList와 LinkedList 또는 List를 구현하는 어떤 객체와도 잘 동작합니다.

 

다음은 이러한 내용을 보여주는 예제 코드이다. (파일명 : ListClientExample.java).

 

 

  public class ListClientExample {

  private List list;

 

  public ListClientExample() {

  list = new LinkedList( );

  }

 

  private List getList() {

  return list;

  }

 

  public static void main(String[ ] args) {

        ListClientExample Ice = new ListClientExample( );

        List list = Ice.getList( );

        System.out.println(list);

  }

 

 

 

 

-Java Collction Framework (JCF)-

 

Java 에서 데이터를 저장하는 기본적인 자료구조들을 한 곳에 모아 관리하고 편하게 사용하기 위해서 제공하는 것을 의미한다.

다음은 JCF 의 상속 구조이며 사용 용도에 따라 List, Set, Map 3가지로 요약할 수 있다.

 

 

 

1. Map

 

키 (Key) 값과 밸류 (Value) 값을 받아 저장하는 함수이다.

 

 

  map<Key,Value>변수 = new HashMap<>( );

 

 

 

 

2. Set

 

String 값으로 저장하는 함수이고, 순서가 없는게 특징이다.

 

 

-예제 및 출력결과-

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
package ch01;
 
import java.awt.List;
import java.util.ArrayList;
import java.util.LinkedList;
 
 
public class ListClientExample {
    
    //list 인스턴스 변수를 선언
    private List list;
    
    public ListClientExample() {
        list = new List();
    }
    
    public List getList() {
        return list;
    }
    
    public static void main(String[] args) {
        ListClientExample Ice = new ListClientExample();
        List list = Ice.getList();
        System.out.println(list);
 
    }
 
}
 
cs

 

 

---작성중---

'Algorithm > 자료구조와 알고리즘' 카테고리의 다른 글

알고리즘 공부순서  (0) 2019.11.04
빅 오 (Big - O) 표기법  (0) 2019.06.16
알고리즘 분석  (0) 2019.06.14
:

19.05.18 jsp 쇼핑몰 차량 상세보기 (동영상 63강)

Back-End/JSP 2019. 5. 18. 21:27

쇼핑몰 차량 상세보기 구현

 

RentcarDAO.java (db연결)

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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
package db;
 
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Vector;
 
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
 
public class RentcarDAO {
 
    Connection con;
    PreparedStatement pstmt;
    ResultSet rs;
 
    // 커넥션풀을 이용한 데이터베이스 연결
 
    public void getcon() {
 
        // DB에 접속할때는 예외처리를 실시해야됨
        try {
 
            Context initctx = new InitialContext(); // 외부서버로 부터 데이터를 읽어들이는것이기 때문에 드라이버가 없을수 있어
            Context envctx = (Context) initctx.lookup("java:comp/env"); // 자바를 읽어들일수 있는 환경에서 사용 //예외처리를 해준다.
            DataSource ds = (DataSource) envctx.lookup("jdbc/pool");
            con = ds.getConnection();
            // 데이터소스에 username, url, password를 집어넣는다. 그렇게 하면 데이터소스가 커넥션을 얻어 온다.
            // jdbc/pool에 있는 데이터소스를 사용할수 있다.
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
 
        }
    }
 
    // 최신순 3대의 자동차를 리턴하는 메소드
    public Vector<CarListBean> getSelectCar() {
        // 리턴타입을 설정
        Vector<CarListBean> v = new Vector<>();
        getcon(); // 커넥션이 연결되어야 쿼리를 실행 가능
 
        try {
 
            String sql = "select * from rentcar order by no desc ";
            pstmt = con.prepareStatement(sql);
            // 쿼리 실행후 실행결과 Result리턴함
            rs = pstmt.executeQuery();
            int count = 0;
            while (rs.next())// 결과값이 끝날때까지만 실행
            {
                CarListBean bean = new CarListBean();
                bean.setNo(rs.getInt(1));
                bean.setName(rs.getString(2));
                bean.setCategory(rs.getInt(3));
                bean.setPrice(rs.getInt(4));
                bean.setUsepeople(rs.getInt(5));
                bean.setCompany(rs.getString(6));
                bean.setImg(rs.getString(7));
                bean.setInfo(rs.getString(8));
                // 벡터에 빈 클래스를 저장
                v.add(bean);
                count++;
                // 3개만 저장이 되야하기 때문..
                if (count > 3)
                    break// 반복문을 빠져나가시오.
 
            }
            con.close();
        } catch (Exception e) {// 내림차순으로 검색하는 쿼리문 작성
            e.printStackTrace();
        }
        return v;
 
    }
 
    // 카테고리별 자동차 리스트를 저장하는 메소드
    // 벡터로 받았으니 벡터로 리턴함..
    public Vector<CarListBean> getCategoryCar(int cate)
 
    {
        // 리턴타입이 벡터 객체이기 때문에 벡터 객체를 생성한다.
        Vector<CarListBean> v = new Vector<>();
 
        // 데이터를 저장할 빈 클래스 선언
        CarListBean bean = null;
 
        getcon();
 
        try {
            String sql = "select * from rentcar where category=?";
            pstmt = con.prepareStatement(sql);
 
            // ?에 값을 넣는다.
            pstmt.setInt(1, cate);
            // 결과를 리턴
            rs = pstmt.executeQuery();
            // 반복문을 돌려서 데이터를 저장
 
            while (rs.next()) { // 데이터를 저장할 빈 클래스 생성
                bean = new CarListBean();
                bean.setNo(rs.getInt(1));
                bean.setName(rs.getString(2));
                bean.setCategory(rs.getInt(3));
                bean.setPrice(rs.getInt(4));
                bean.setUsepeople(rs.getInt(5));
                bean.setCompany(rs.getString(6));
                bean.setImg(rs.getString(7));
                bean.setInfo(rs.getString(8));
                // 벡터에 빈 클래스를 저장
                v.add(bean);
 
            }
 
            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        return v;
 
    }
 
    // 모든 차량을 검색하는 메소드
    public Vector<CarListBean> getAllCar() {
 
        Vector<CarListBean> v = new Vector<>();
        // 데이터를 저장할 빈클래스 선언
        CarListBean bean = null;
 
        getcon();
 
        try {
            String sql = "select * from rentcar";
            pstmt = con.prepareStatement(sql);
            rs = pstmt.executeQuery();
            // 반복문을 돌리면서 데이터를 저장함
 
            while (rs.next()) {// 데이터를 저장할 빈클래스 생성
                bean = new CarListBean();
                bean.setNo(rs.getInt(1));
                bean.setName(rs.getString(2));
                bean.setCategory(rs.getInt(3));
                bean.setPrice(rs.getInt(4));
                bean.setUsepeople(rs.getInt(5));
                bean.setCompany(rs.getString(6));
                bean.setImg(rs.getString(7));
                bean.setInfo(rs.getString(8));
                // 벡터에 빈 클래스를 저장
                v.add(bean);
 
            }
 
            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return v;
 
    }
 
    // 하나의 자동차 정보를 리턴하는 메소드
    public CarListBean getOneCar(int no) {
 
        // 리턴타입을 선언한다. 객체를 생성해서 그 객체에 값을 넣은후 리턴해야하기 때문
        CarListBean bean = new CarListBean();
 
        getcon();
 
        try {
            String sql = "select * from rentcar where no=?";
            pstmt = con.prepareStatement(sql);
            // sql문에 ?표가 들어가 있으면 초기 인덱스 값을 할당해주어야 한다.
            pstmt.setInt(1, no);
            rs = pstmt.executeQuery();
 
            if (rs.next()) {
                bean.setNo(rs.getInt(1));
                bean.setName(rs.getString(2));
                bean.setCategory(rs.getInt(3));
                bean.setPrice(rs.getInt(4));
                bean.setUsepeople(rs.getInt(5));
                bean.setCompany(rs.getString(6));
                bean.setImg(rs.getString(7));
                bean.setInfo(rs.getString(8));
 
            }
 
            con.close();
 
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bean;
 
    }
 
}
 
cs

 

 

CarReserveInfo.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
<%@page import="db.CarListBean"%>
<%@page import="db.RentcarDAO"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
 
<% 
    //차량의 상세정보를 보기위해 no값을 가져온다.
    int no = Integer.parseInt(request.getParameter("no"));
 
    //데이터베이스에 접근
    RentcarDAO rdao = new RentcarDAO();
    //렌트카 하나에 대한 정보를 얻어옴
    CarListBean bean = rdao.getOneCar(no);
    
    int category = bean.getCategory();
    String temp = "";
    if (category == 1)
        temp = "소형";
    else if (category == 2)
        temp = "중형";
    else if (category == 3)
        temp = "대형";
    
%>
<center>
<form action="RentcarMain.jsp?center=CarOptionSelect.jsp"></form>
<table width= "1000" >
<tr height="100">
            <td align="center" colspan="3"><font size="6" color="gray">
                        <%=bean.getName() %> 차량 선택
                </font></td>
            </tr>
            <tr>
            <!-- colspan은 가로셀끼리 병합하는 것이고, rowspan은 세로 셀끼리 병합하는 것 -->
            <!-- 차량 사진 옆에 정보들이 떠야하기때문에 세로병합인 rowspan을 사용 -->
            <td rowspan="6" width="500" align="center">
            <img alt="" src="img/<%=bean.getImg()%>" width="450"></td>
            <td width="250" align="center"> 차량이름</td>
            <td width="250" align="center"> <%=bean.getName() %></td>
            </tr>
            
            <tr>
            <td width="250" align="center"> 차량수량</td>
            <td width="250" align="center"> <select name = "qty">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            </select>
            </td>
            </tr>
            
            
            <tr>
            <td width="250" align="center"> 차량분류</td>
            <td width="250" align="center"> <%=temp %>
            </tr>
            
            <tr>
            <td width="250" align="center"> 대여가격</td>
            <td width="250" align="center"> <%=bean.getPrice() %></td>
            </tr>
            
            <tr>
            <td width="250" align="center"> 제조회사</td>
            <td width="250" align="center"> <%=bean.getCompany() %></td>
            </tr>
            
            <tr>
            <td align="center" colspan="2">
                <input type = "hidden" name ="no" value="<%=bean.getNo() %>">
                <input type="submit" value="옵션선택후 구매하기">
                </td>
            </tr>
</table>
<br><br><br>
<font size="6" color="gray"> 차량 정보 보기 </font>
<p>
<%=bean.getInfo() %>
</center>
</body>
</html>
cs

 

 

 

:

19.05.18 jsp 쇼핑몰 차량 전체보기 (동영상 62강)

Back-End/JSP 2019. 5. 18. 18:09

쇼핑몰 차량 전체 보기 구현

 

 

RentcarMain.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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
 
    <%
        String center = request.getParameter("center");
        //처음 실행시에는 center 값이 넘어오지 않기에 반드시  null처리를 해야한다.
        //처리를 하지않으면 에러가 발생될수 있다.
 
        if (center == null) {
            center = "Center.jsp"//디폴트 center값을 부여(첫 화면에는 center이 뜨도록 한다는 말)    
        }
    %>
    <center>
        <table width="1000">
 
            <!-- Top 부분 -->
            <tr height="140" align="center">
                <!-- include page를 사용하여서 main페이지에서 각 페이지가 호출될수 있도록 한다. -->
                <td align="center" width="1000"><jsp:include page="Top.jsp" /></td>
            </tr>
 
            <!-- Center 부분 -->
            <!-- Top랑,Bottom은 화면이 넘어가더라도 바뀌지 않지만 center은 계속 바뀌기 때문에 center값을 준다 -->
 
            <tr height="100" align="center">
                <td align="center" width="1000"><jsp:include
                        page="<%=center%>" /></td>
            </tr>
 
            <!-- Bottom 부분 -->
            <tr height="140" align="center">
                <td align="center" width="1000"><jsp:include page="Bottom.jsp" /></td>
            </tr>
 
        </table>
    </center>
</body>
</html>
 
cs

 

 

Top.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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
 
    <!-- 세션을 이용한 로그인 처리 -->
    <!-- 세션으로 받아온 값은 오브젝트 타입이기 때문에 String 타입으로 컨버팅 한다. -->
 
    <%
        String id = (String) session.getAttribute("id");
 
        //로그인이 되어있지 않다면 id에 "GUEST"값을 준다
        if (id == null) {
            id = "GUEST";
        }
    %>
 
    <table width="1000" bordercolor="white">
        <tr height="70">
            <td colspan="4"><a href="RentcarMain.jsp"
                style="text-decoration: none"> <!-- 이미지를 불러오기위한 태그 작성 --> <img
                    alt="" src="img/RENT.jpg" height="150" width="250">
            </a></td>
            <td align="center" width="200"><%=id%> 님 반갑습니다.</td>
        </tr>
        <!-- 글자를 누르면 화면이 넘어갈수 있도록 a태그를 걸어줌 -->
        <tr height="50">
            <td align="center" width="200" bgcolor="pink"><font
                color="white" size="5"> <a
                    href="RentcarMain.jsp?center=CarReserveMain.jsp"
                    style="text-decoration: none"> 예 약 하 기 </a></font></td>
 
            <td align="center" width="200" bgcolor="pink">
                <!-- 글자를 누르면 화면이 넘어갈수 있도록 a태그를 걸어줌 --> <font color="white" size="5"><a
                    href="#" style="text-decoration: none"> 예 약 확 인</a></font>
            </td>
 
            <td align="center" width="200" bgcolor="pink">
                <!-- 글자를 누르면 화면이 넘어갈수 있도록 a태그를 걸어줌 --> <font color="white" size="5"><a
                    href="#" style="text-decoration: none"> 자 유 게 시 판 </a></font>
            </td>
 
            <td align="center" width="200" bgcolor="pink">
                <!-- 글자를 누르면 화면이 넘어갈수 있도록 a태그를 걸어줌 --> <font color="white" size="5"><a
                    href="#" style="text-decoration: none"> 이 벤 트 </a></font>
            </td>
 
            <td align="center" width="200" bgcolor="pink">
                <!-- 글자를 누르면 화면이 넘어갈수 있도록 a태그를 걸어줌 --> <font color="white" size="5"><a
                    href="#" style="text-decoration: none"> 고 객 센 터 </a></font>
            </td>
        </tr>
 
    </table>
</body>
</html>
 
cs

 

 

Center.jsp (중간)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
    <center>
        <table width="1000">
            <tr height="600">
                <!-- 센터에 출력될 이미지를 추가 -->
                <td align="center"><img alt="" src="img/Main.jpg" height="470"
                    width="1000"></td>
            </tr>
        </table>
    </center>
</body>
</html>
 
cs

 

 

Bottom.jsp (하단)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
    <center>
        <table width="1000">
            <tr height="100">
                <td align="center">
                    <hr color="red" size="5"> 이용약관 이메일 무단수집거부 개인정보 취급(처리)방침 윤리경영
                    보안신고 Contact Us 사업장 소개 사이트맵 웹접근성 도움말<br> 배드민턴단 COPYRIGHT@2015
                    SAMSUNG ELECTRO-MECHANICS, All rights reserved.
                </td>
            </tr>
        </table>
    </center>
</body>
</html>
 
cs

 

 

CarReserveMain.jsp (최신 자동차 3대 출력)

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
<%@page import="db.CarListBean"%>
<%@page import="java.util.Vector"%>
<%@page import="db.RentcarDAO"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
    <center>
 
        <!-- 데이터베이스에 연결하여 최신순 자동차 3대만 뿌려주는 데이터를 가져옴 -->
 
        <%
            RentcarDAO rdao = new RentcarDAO();
            //벡터를 이용하여 자동차데이터를 저장함
            Vector<CarListBean> v = rdao.getSelectCar();
        %>
 
        <table width="1000">
            <tr height="100">
                <td align="center" colspan="3"><font size="6" color="gray">최신형
                        자동차</font></td>
            </tr>
 
 
            <tr height="240">
                <!-- 벡터에 저장된 이미지를 하나씩 출력해야하기 때문에 for문을 돌리고, 그 값들을 빈클래스 변수에 넣어준다. -->
                <%
                    for (int i = 1; i < v.size(); i++) {
                        CarListBean bean = v.get(i);
                %>
                <td width="333" align="center">
                    <!-- 이미지는 벡터의 0번지에 해당되는걸 가져온다. for문을 돌려 td를 출력해야 한다.--> <!-- 확장자는 이미지안에 있으므로 궂이 적지 않아도 된다. -->
                    <!-- 이미지를 누르면 바로 상세정보로 넘어갈수 있도록 하기위해  <a>태그를 걸고, No에 대한 상세정보가 출력되도록 하고
        이름을 사진밑에 출력하도록 한다. --> <a
                    href="CarReserveInfo.jsp?no=<%=bean.getNo()%>"> <img alt=""
                        src="img/<%=bean.getImg()%>" width="300" height="220">
                </a>
                    <p>
                        차량명 :
                        <%=bean.getName()%>
                </td>
 
 
                <%
                    }
                %>
            
        </table>
 
        <p>
            <font size="4" color="gray"> 차량 검색 하기 </font><br> <br> <br>
            <!-- 종류를 선택하고 검색을 하면 종류라는 데이터들 가지고 넘어가야하기 때문에 form형식을 사용한다. -->
        <form action="RentcarMain.jsp?center=CarCategoryList.jsp"
            method="post">
            <font size="3" color="gray"> <b>차량 검색 하기</b>
            </font>&nbsp;&nbsp; <select name="category">
                <option value="1">소형</option>
                <option value="2">중형</option>
                <option value="3">대형</option>
            </select>&nbsp;&nbsp; <input type="submit" value="검색"> &nbsp;&nbsp;
 
        </form>
        <button
            onclick="location.href='RentcarMain.jsp?center=CarAllList.jsp'">전체
            검색</button>
 
    </center>
</body>
 
</html>
 
cs

 

 

CarCategoryList.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
<%@page import="db.CarListBean"%>
<%@page import="java.util.Vector"%>
<%@page import="db.RentcarDAO"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
    <!-- 카테고리 분류값을 받아와서 소형,중형, 대형에 따라 화면에 출력함 -->
    <%
        int category = Integer.parseInt(request.getParameter("category"));
        String temp = "";
        if (category == 1)
            temp = "소형";
        else if (category == 2)
            temp = "중형";
        else if (category == 3)
            temp = "대형";
    %>
    <center>
        <table width="1000">
            <tr height="100">
                <td align="center" colspan="3"><font size="6" color="gray">
                        <%=temp%>자동차
                </font></td>
            </tr>
            <%
                //카테고리 분류값을 받아온다. (검색의 기준으로 삼아야하기 때문)
                //CarRserveMain페이지 에서 //select 옵션으로 준 값들을 가져온다.
                //소형=1, 중형=2 등등등
                //request.getParameter 값은 다 string 타입이기때문에 포장클래스를 사용해 타입변환을 한다.
 
                System.out.println("category");
 
                //DB연결을 위해 객체를 생성
                RentcarDAO rdao = new RentcarDAO();
 
                //값이 유동적이기 때문에 벡터로 받고, 파라미터로 받은 category (분류값들)를 매개값으로 준다.
                Vector<CarListBean> v = rdao.getCategoryCar(category);
 
                //tr을 3개씩 보여주고 다시 tr을 실행할 수 있도록 하는 변수 선언
                int j = 0;
                for (int i = 0; i < v.size(); i++) {
                    //벡터에 저장되어 있는 빈 클래스를 추출
                    CarListBean bean = v.get(i);
                    //3번마다 0이 돌아온다는 뜻. 즉 3번에 한번 실행하도록 하는 구문
                    if (j % 3 == 0) {
            %>
            <tr height="220">
                <%
                    }
                %>
                <td width="333" align="center"><a
                    href="RentcarMain.jsp?center=CarReserveInfo.jsp?no=<%=bean.getNo()%>">
                        <img alt="" src="img/<%=bean.getImg()%>" width="300" height="200">
                </a>
                    <p>
                        <font size="3" color="gray"><b>차량명 : <%=bean.getName()%>
                        </b> </font></td>
 
 
 
                <%
                    j = j + 1//j값을 증가하여 하나의 행에 총3개의 차량정보를 보여주기 위해서 증가
                    }
                %>
            
        </table>
    </center>
</body>
</html>
cs

 

 

CarAllList.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="db.CarListBean"%>
<%@page import="java.util.Vector"%>
<%@page import="db.RentcarDAO"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
    <center>
        <table width="1000">
            <tr height="100">
                <td align="center" colspan="3"><font size="6" color="gray">
                        전체 렌트카 보기 </font></td>
            </tr>
            <%
                //DB연결을 위해 객체를 생성
                RentcarDAO rdao = new RentcarDAO();
 
                //값이 유동적이기 때문에 벡터로 받고, 파라미터로 받은 category (분류값들)를 매개값으로 준다.
                Vector<CarListBean> v = rdao.getAllCar();
 
                //tr을 3개씩 보여주고 다시 tr을 실행할 수 있도록 하는 변수 선언
                int j = 0;
                for (int i = 0; i < v.size(); i++) {
                    //벡터에 저장되어 있는 빈 클래스를 추출
                    CarListBean bean = v.get(i);
                    //3번마다 0이 돌아온다는 뜻. 즉 3번에 한번 실행하도록 하는 구문
                    if (j % 3 == 0) {
            %>
            <tr height="220">
                <%
                    }
                %>
                <td width="333" align="center"><a
                    href="RentcarMain.jsp?center=CarReserveInfo.jsp?no=<%=bean.getNo()%>">
                        <img alt="" src="img/<%=bean.getImg()%>" width="300" height="200">
                </a>
                    <p>
                        <font size="3" color="gray"><b>차량명 : <%=bean.getName()%>
                        </b> </font></td>
 
 
 
                <%
                    j = j + 1//j값을 증가하여 하나의 행에 총3개의 차량정보를 보여주기 위해서 증가
                    }
                %>
            
        </table>
    </center>
</body>
 
</html>
cs

 

 

CarListBean.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
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
package db;
 
public class CarListBean { // 빈 클래스 생성함
 
    private int no;
    private String name;
    private int category;
    private int price;
    private int usepeople;
    private String company;
    private String img;
    private String info;
 
    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 int getCategory() {
        return category;
    }
 
    public void setCategory(int category) {
        this.category = category;
    }
 
    public int getPrice() {
        return price;
    }
 
    public void setPrice(int price) {
        this.price = price;
    }
 
    public int getUsepeople() {
        return usepeople;
    }
 
    public void setUsepeople(int usepeople) {
        this.usepeople = usepeople;
    }
 
    public String getImg() {
        return img;
    }
 
    public void setImg(String img) {
        this.img = img;
    }
 
    public String getInfo() {
        return info;
    }
 
    public void setInfo(String info) {
        this.info = info;
    }
 
    public String getCompany() {
        return company;
    }
 
    public void setCompany(String company) {
        this.company = company;
    }
}
 
cs

 

 

RentcarDAO.java (db연결)

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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
package db;
 
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Vector;
 
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
 
public class RentcarDAO {
 
    Connection con;
    PreparedStatement pstmt;
    ResultSet rs;
 
    // 커넥션풀을 이용한 데이터베이스 연결
 
    public void getcon() {
 
        // DB에 접속할때는 예외처리를 실시해야됨
        try {
 
            Context initctx = new InitialContext(); // 외부서버로 부터 데이터를 읽어들이는것이기 때문에 드라이버가 없을수 있어
            Context envctx = (Context) initctx.lookup("java:comp/env"); // 자바를 읽어들일수 있는 환경에서 사용 //예외처리를 해준다.
            DataSource ds = (DataSource) envctx.lookup("jdbc/pool");
            con = ds.getConnection();
            // 데이터소스에 username, url, password를 집어넣는다. 그렇게 하면 데이터소스가 커넥션을 얻어 온다.
            // jdbc/pool에 있는 데이터소스를 사용할수 있다.
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
 
        }
    }
 
    // 최신순 3대의 자동차를 리턴하는 메소드
    public Vector<CarListBean> getSelectCar() {
        // 리턴타입을 설정
        Vector<CarListBean> v = new Vector<>();
        getcon(); // 커넥션이 연결되어야 쿼리를 실행 가능
 
        try {
 
            String sql = "select * from rentcar order by no desc ";
            pstmt = con.prepareStatement(sql);
            // 쿼리 실행후 실행결과 Result리턴함
            rs = pstmt.executeQuery();
            int count = 0;
            while (rs.next())// 결과값이 끝날때까지만 실행
            {
                CarListBean bean = new CarListBean();
                bean.setNo(rs.getInt(1));
                bean.setName(rs.getString(2));
                bean.setCategory(rs.getInt(3));
                bean.setPrice(rs.getInt(4));
                bean.setUsepeople(rs.getInt(5));
                bean.setCompany(rs.getString(6));
                bean.setImg(rs.getString(7));
                bean.setInfo(rs.getString(8));
                // 벡터에 빈 클래스를 저장
                v.add(bean);
                count++;
                // 3개만 저장이 되야하기 때문..
                if (count > 3)
                    break// 반복문을 빠져나가시오.
 
            }
            con.close();
        } catch (Exception e) {// 내림차순으로 검색하는 쿼리문 작성
            e.printStackTrace();
        }
        return v;
 
    }
 
    // 카테고리별 자동차 리스트를 저장하는 메소드
    // 벡터로 받았으니 벡터로 리턴함..
    public Vector<CarListBean> getCategoryCar(int cate)
 
    {
        // 리턴타입이 벡터 객체이기 때문에 벡터 객체를 생성한다.
        Vector<CarListBean> v = new Vector<>();
 
        // 데이터를 저장할 빈 클래스 선언
        CarListBean bean = null;
 
        getcon();
 
        try {
            String sql = "select * from rentcar where category=?";
            pstmt = con.prepareStatement(sql);
 
            // ?에 값을 넣는다.
            pstmt.setInt(1, cate);
            // 결과를 리턴
            rs = pstmt.executeQuery();
            // 반복문을 돌려서 데이터를 저장
 
            while (rs.next()) { // 데이터를 저장할 빈 클래스 생성
                bean = new CarListBean();
                bean.setNo(rs.getInt(1));
                bean.setName(rs.getString(2));
                bean.setCategory(rs.getInt(3));
                bean.setPrice(rs.getInt(4));
                bean.setUsepeople(rs.getInt(5));
                bean.setCompany(rs.getString(6));
                bean.setImg(rs.getString(7));
                bean.setInfo(rs.getString(8));
                // 벡터에 빈 클래스를 저장
                v.add(bean);
 
            }
 
            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        return v;
 
    }
 
    // 모든 차량을 검색하는 메소드
    public Vector<CarListBean> getAllCar() {
 
        Vector<CarListBean> v = new Vector<>();
        // 데이터를 저장할 빈클래스 선언
        CarListBean bean = null;
 
        getcon();
 
        try {
            String sql = "select * from rentcar";
            pstmt = con.prepareStatement(sql);
            rs = pstmt.executeQuery();
            // 반복문을 돌리면서 데이터를 저장함
 
            while (rs.next()) {// 데이터를 저장할 빈클래스 생성
                bean = new CarListBean();
                bean.setNo(rs.getInt(1));
                bean.setName(rs.getString(2));
                bean.setCategory(rs.getInt(3));
                bean.setPrice(rs.getInt(4));
                bean.setUsepeople(rs.getInt(5));
                bean.setCompany(rs.getString(6));
                bean.setImg(rs.getString(7));
                bean.setInfo(rs.getString(8));
                // 벡터에 빈 클래스를 저장
                v.add(bean);
 
            }
 
            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return v;
 
    }
 
}
 
cs

 

 

 

: