Notice
Recent Posts
Recent Comments
Link
«   2025/03   »
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
Archives
Today
Total
관리 메뉴

개발자

[JSP 4일차]fmt/Oracle과 연동/ 본문

개발자/JSP

[JSP 4일차]fmt/Oracle과 연동/

GoGo개발 2022. 9. 1. 11:54
Oracle과 연동

 

view 단페이지 jsp는 WEB-INF 에서 만든다. 직접돌렸을때 페이지가 나오지 않고, http://localhost:9090/JSPServletBegin/personRegister.do 주소를 입력해야지 페이지가 나오게 하기위해서
직접적인 경로명을 알수 없어서 보안성이 좋다

접속 >> 
http://localhost:9090/JSPServletBegin/personRegister.do

1.서블릿에서 forward 로 view단 페이지jsp를 보여준다. <PersonRegister_01> <personRegister.jsp>
2.초기 개인성향입력 jsp view단 페이지에서 데이터를 입력받는다 < personRegister.jsp>
3.서블릿에서 jsp받은 데이터를 서블릿에서 불러와서 DB로 보내준다 <폼태크에서 데이터 가져와서 6번>
( WEB-INF에 오라클 폴더를 만들어서 오라클을 추가해준다)
4.DB에 테이블 생성
5.DTO만들어서 DB에 있는 테이블 컬럼들 가져오고, getter setter 해준다
6.서블릿에서f orm 태그에서 가져온 데이터를 DTO에 담아서 DAO에보내 DB에 저장하기위해서
    DTO set해서 dto에 데이터 담아주기

7.interDAO DAO 생성후 , 서블릿에 dao 객체생성
8.interdao 추상메소드 생성후( 개인성향을 입력(insert)해주는 추상메소드) /  dao에서 오버라이딩
9.MyDBConnection_05 생성
10.dao에서 던져준 오류처리를 포함해 db전송(Dao) 성공,실패시 넘어가는 veiw단 페이지로 forward 해주기
 포워드해준곳에서만 SetAttribute 되어진 데이터를 꺼내 볼 수 있다.

11.성공,실패 view 단 jap 만들기 (10번에 연결)  <personRegister_success.jsp>

 

1. 서블릿(java)에서 : 1번  3번  6번  7번  10번 <PersonRegister_01>

:personRegister.jsp, personRegister_success.jsp 이곳만 포워드해주었기 때문에 여기서만 SetAttribute 되어진 paraMap을 꺼내 볼 수 있다.

 

 

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
package chap05.oracle;
 
import java.io.IOException;
 
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
@WebServlet("/personRegister.do")
public class PersonRegister_01 extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    //7번 dao 객체생성
    InterPersonDAO_03 dao = new PersonDAO_04();
 
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        String method = request.getMethod(); //"GET" 또는 "POST"
        
        if("GET".equalsIgnoreCase(method)) {
            // == http://localhost:9090/JSPServletBegin/personRegister.do 을 하면 회원성향 입력창을 띄우도록 한다. == 
        
        // 회원성향입력창은 get으로 submit했을때는(action 단) post방식을 쓰겠다 2개를 동시에 쓰겠다    
        // 이때는 두페이지의 URL이 똑같다 
            
    //    RequestDispatcher dispatcher = request.getRequestDispatcher("/chap05_mistake/personRegister.jsp");
    //  위는 잘못된 곳 아래가 올바른 곳    
        RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/chap_right/personRegister.jsp");
        //view 단페이지 jsp는 WEB-INF 에서 만든다 직접돌렸을때 페이지가 나오지 않고,
        //http://localhost:9090/JSPServletBegin/personRegister.do 주소를 입력해야지 페이지가 나오게 하기위해서
        //직접적인 경로명을 알수 없어서 보안성이 좋다
        dispatcher.forward(request, response);
            
        }
 
        else {
            // POST 방식으로 http://localhost:9090/JSPServletBegin/personRegister.do 을 호출한 경우이라면 
            // 서브밋 되어져온 데이터를 받아서 DB로 보내야 한다.  
            
        //3번 폼태크에서 데이터 가져와서 6번
        String name = request.getParameter("name"); //form태그 데이터 받아오기
        String school = request.getParameter("school");
        String color = request.getParameter("color");
        String[] foodArr = request.getParameterValues("food");
        
        //DTO 나 MAP에 담아서 DAO에 보내준다
        
        //유효성 검사해서 null 값 들어올수없고, post방식에서만 작동한다/ food는 null값 허용
        
        // 6번 dto에 담아주기 dao에 보내기위해서 
        PersonDTO_02 psdto = new PersonDTO_02();
        psdto.setName(name);
        psdto.setSchool(school);
        psdto.setColor(color);
        psdto.setFood(foodArr);
        
        //10번 dao에서 던져준 오류를 포함해 성공,실패시 넘어가는 veiw단 페이지로 forward 해주기
        String pathname= "";
        try {
            int n = dao.personRegister(psdto);
            
            if(n==1) { //DB전송(dao) 성공하면 성공페이지 
                pathname = "/WEB-INF/chap_right/personRegister_success.jsp";
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            pathname = "/WEB-INF/chap_right/personRegister_fail.jsp"// 실패하면 보여지는 페이지
        }
        
        RequestDispatcher dispatcher = request.getRequestDispatcher(pathname);
        dispatcher.forward(request, response);
        }
    }
 
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        doGet(request, response);
    }
 
}
 
cs

 

2. 초기 개인성향입력 jps veiw단 페이지 : 2번

 

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
</style>
 
<script type="text/javascript" src="<%= ctxPath%>/js/jquery-3.6.0.min.js"></script> 
<script type="text/javascript">
 
   $(document).ready(function(){
       
   //  $("form[name='registerFrm']").bind("submit", function(){
   //  또는      
   //  $("form[name='registerFrm']").submit(function(){     
   //  또는      
       $("form[name='registerFrm']").submit(() => {                
       
           // === 유효성 검사 === //
           // 1. 성명
           const name_length = $("input:text[name='name']").val().trim().length;
           if(name_length == 0) {
               alert("성명을 입력하세요!!");
               $("input:text[name='name']").val("").focus();
               return false// submit 을 하지 않고 종료한다.
           }
           
           // 2. 학력
           const school_val = $("select[name='school']").val();
           if(school_val == "") {
               alert("학력을 선택하세요!!");
               return false// submit 을 하지 않고 종료한다.
           }
           
           // 3. 색상
           const color_length = $("input:radio[name='color']:checked").length
           if(color_length == 0) {
               alert("색상을 선택하세요!!");
               return false// submit 을 하지 않고 종료한다.
           }
           
           // 4. 음식은 좋아하는 음식이 없다라면 선택을 안하더라도 허용하겠다.
           
           //null값 허락해주겠다 아래 유효성검사 없앴으니까
         /*   const food_length = $("input:checkbox[name='food']:checked").length; 
           if(food_length == 0) {
               alert("선호하는 음식을 최소한 1개 이상 선택하세요!!");
               return false; // submit 을 하지 않고 종료한다.
           }
            */
       });// end of $("form#registerFrm").submit(function(){})------------
       
   });// end of $(document).ready()----------------------------
 
</script>
 
</head>
<body>
 
    <form name="registerFrm" action="<%= ctxPath%>/personRegister.do" method="post">
        <fieldset>
            <legend>개인성향 데이터를 DB로 전송하기</legend>
            <ul>
                <li>
                    <label for="name">성명</label>
                    <input type="text" name="name" placeholder="성명입력"/> 
                </li>
                <li>
                    <label for="school">학력</label>
                    <select name="school">
                        <option value="">선택하세요</option>
                        <option>고졸</option>
                        <option>초대졸</option>
                        <option>대졸</option>
                        <option>대학원졸</option>
                    </select>
                </li>
                <li>
                    <label for="">좋아하는 색상</label>
                    <div>
                        <label for="red">빨강</label>
                        <input type="radio" name="color" id="red" value="red" />
                        
                        <label for="blue">파랑</label>
                        <input type="radio" name="color" id="blue" value="blue" />
                        
                        <label for="green">초록</label>
                        <input type="radio" name="color" id="green" value="green" />
                        
                        <label for="yellow">노랑</label>
                        <input type="radio" name="color" id="yellow" value="yellow" />
                    </div>
                </li>
                <li>
                    <label for="">좋아하는 음식(다중선택)</label>
                    <div>
                        <label for="food1">짜짱면</label>
                        <input type="checkbox" name="food" id="food1" value="짜짱면" />
                        &nbsp;
                        
                        <label for="food2">짬뽕</label>
                        <input type="checkbox" name="food" id="food2" value="짬뽕" />
                        &nbsp;
                        
                        <label for="food3">탕수육</label>
                        <input type="checkbox" name="food" id="food3" value="탕수육" />
                        &nbsp;
                        
                        <label for="food4">양장피</label>
                        <input type="checkbox" name="food" id="food4" value="양장피" />
                        &nbsp;
                        
                        <label for="food5">팔보채</label>
                        <input type="checkbox" name="food" id="food5" value="팔보채" />
                    </div>
                </li>
                <li>
                    <input type="submit" value="전송" />
                    <input type="reset" value="취소" />
                </li>
            </ul>
        </fieldset>
    </form>
 
</body>
</html>
cs

 

 

개인성향 데이터를 DB로 전송하기
  •        

 

 

3. 오라클 DB  :4번 

 3-1 환경설정

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
show user;
--USER이(가) "SYS"입니다.
 
--오라클 계정생성시 계정명앞에 c## 을 붙이지 않고 생성하도록 하겠다.
alter session set "_ORACLE_SCRIPT" = true;
--Session이(가) 변경되었습니다.
--그러면 이제부터는 계정생성시 c## 없이 계정 생성이 가능하다.
 
create user jspbegin_user identified by aclass default tablespace users;
--User JSPBEGIN_USER이(가) 생성되었습니다. 
--비밀번호 aclass
 
grant connect, resource, create view, unlimited tablespace to jspbegin_user;
--Grant을(를) 성공했습니다.
--권한을 주는 것이다. 그냥 이렇다고 알아둬라.
 
show user;
--USER이(가) "JSPBEGIN_USER"입니다.
cs

 

 3-2  테이블 만들기

 

 

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
create table tbl_person_interest
(seq         number
,name        Nvarchar2(20not null
,school      Nvarchar2(10not null
,color       Nvarchar2(10not null
,food        Nvarchar2(40
,registerday date default sysdate
,constraint PK_tbl_person_interest_seq primary key(seq)
);
--Table TBL_PERSON_INTEREST이(가) 생성되었습니다.
 
alter table tbl_person_interest
modify food null;
--내가 food에 null 허용해주어야하는데 not null 해놨어서 null허용으로 컬럼변경해주었다
 
desc tbl_person_interest;
--테이블 확인
 
create sequence person_seq
start with 1
increment by 1
nomaxvalue
nominvalue
nocycle
nocache;
--Sequence PERSON_SEQ이(가) 생성되었습니다.
 
 
select seq, name, school, color, food, to_char(registerday, 'yyyy-mm-dd hh24:mi:ss') AS registerday
from tbl_person_interest
order by seq;
cs

 

지금은 테이블에 아무 데이터도 없다

 

5 DTO : 5번

 

 

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
package chap05.oracle;
 
public class PersonDTO_02 {
 
    //DB 테이블 컬럼들 가져오기
    private int seq;      
    private String name;    
    private String school;    
    private String color;       
    private String[] food;      
    private String registerday;
    
    //getter setter
    
    public int getSeq() {
        return seq;
    }
    public void setSeq(int seq) {
        this.seq = seq;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSchool() {
        return school;
    }
    public void setSchool(String school) {
        this.school = school;
    }
    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }
    public String[] getFood() {
        return food;
    }
    public void setFood(String[] food) {
        this.food = food;
    }
    public String getRegisterday() {
        return registerday;
    }
    public void setRegisterday(String registerday) {
        this.registerday = registerday;
    }
 
    
}
 
cs

 

6.DAO : 7번 8번

 

<interDAO>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package chap05.oracle;
 
import java.sql.SQLException;
import java.util.List;
 
public interface InterPersonDAO_03 {
    
    //개인성향을 입력(insert)해주는 추상메소드(미완성메소드)
    int personRegister(PersonDTO_02 psdto) throws SQLException;
    //파라미터 DTO 데이터필요하니까 DTO 넣어준다
    
    
}
 
 
cs

 

 

<DAO>

 

 

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
package chap05.oracle;
 
import java.sql.*;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.List;
 
 
 
public class PersonDAO_04 implements InterPersonDAO_03 {
 
    private Connection conn;
    private PreparedStatement pstmt;
    private ResultSet rs;
    
    
    private void close() { //자원반납 메소드
        try {
            if(rs !=null) {rs.close(); rs=null;}
            if(pstmt !=null) {pstmt.close(); pstmt=null;}
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }
 
    //개인성향을 입력(insert)해주는 메소드
    @Override
    public int personRegister(PersonDTO_02 psdto) throws SQLException {
        
        int n = 0;
        
        try {
        //싱클톤 패턴기법
        conn = MyDBConnection_05.getConn();
        
        //db에서 java로변환해왔음 
        String sql = " insert into tbl_person_interest( seq, name, school, color, food) "
                     + " values(person_seq.nextval, ?, ?, ?, ?) ";
        
        //sql 전달할 우편배달부
        pstmt = conn.prepareStatement(sql);        
        
        //위치홀더(?)에 값 맵핑시키기    
        pstmt.setString(1, psdto.getName());
        pstmt.setString(2, psdto.getSchool());
        pstmt.setString(3, psdto.getColor());
        
        //Food는 null 있으니까
        if( psdto.getFood() != null ) {
            pstmt.setString(4String.join(",", psdto.getFood()));
        }
        else {
            pstmt.setString(4,null);
            
        }
        
        // 우리는 오류 throws 하기로했으니까 exception 처리는 서블릿에서 해준다.
        n = pstmt.executeUpdate();
        }finally {
            close(); // 자원반납        
        }
    
        return n;
    }// end of public int personRegister(PersonDTO_02 psdto) throws SQLException
 
}
 
cs

 

7.dbconneciton

 

 

8. 성공, 실패시 보여주는 veiw단 페이지 : 11번 <personRegister_success.jsp>

 

<success 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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<%
    String ctxPath = request.getContextPath();
    // ctxPath ==> /JSPServletBegin
%>    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>개인성향 입력한 결과가 성공인 경우에 보여주는 페이지</title>
 
<script type="text/javascript">
 
    
    //다시시작 1번
    //Function Declaration
    function goSelect() {
        
        // === !! 암기 !! ===//
        // 자바스크립트에서 URL 페이지의 이동은 location.href="이동할 URL 경로명"; 으로 하면 된다.
        
        location.href="<%= ctxPath%>/personSelect.do";
        
    }// end of function goSelect(){}----------------------
 
</script>
 
</head>
<body>
    <h2>개인성향 입력 성공</h2>
    <br>
    <button onclick= "goSelect()">입력결과 조회하기</button>
</body>
</html>
cs

 

 

 

<fail jsp>

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>개인성향 입력한 결과가 실패한 경우에 보여주는 페이지<</title>
</head>
<body>
    <h2 style="color:red;">장애발생으로 인해 개인성향 입력 실패</h2>
 
</body>
</html>
cs

 

 

다시 시작 

1.성공, 실패시 보여주는 veiw단 페이지에서 자바스크립트이용해  <위의 success jsp>
location.href="이동할 URL 경로명"; 해서 보여줄 페이지로 이동시켜준다
  ==> select all 성공시 보여주는  veiw 단 페이지
personRegister_success.jsp ==> personSelectAll.jsp
personRegister.do ==>  "personSelect.do"


접속 >> http://localhost:9090/JSPServletBegin/personSelect.do

2.보여줄 페이지와 맵핑할 06 서블릿 만들어주기 (새로운 서블릿) <PersonSelect_06>

3.interdao selectall 메소드 만들어주고  dao에서 오버라이딩  (select한거 dto에 담아주기) <기존 dao>
테이블에 저장되어진 모든 행들을 select 해주는 추상메소드


4. 06서블릿에가서  dao에서 던져준 오류처리를 포함해 db에서 불러오기(Dao) 성공,실패시 넘어가는 
    veiw단 페이지로 forward 해주기  

5. 성공,실패시 보여줄 view 단 jsp 만들기 / 다음페이지로 이동
location.href="이동할 URL 경로명"; 해서 보여줄 페이지로 이동시켜준다

personSelectAll.jsp ==> personDetail.jsp
"personSelect.do"   ==> "personDetail.do?seq="+seq;


6.정보 눌렀을때 보여주는 veiw 단 jsp 만들기 (5번 페이지에서 선택)

1. register 성공, 실패시 보여주는 veiw단 페이지 : 1번

  ==> select all 성공시 보여주는  veiw 단 페이지

 

personRegister_success.jsp ==> personSelectAll.jsp

personRegister.do ==>  "personSelect.do"  

 

<성공할 시 >

 

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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
    
<%@ page import="java.util.* , chap05.oracle.PersonDTO_02" %>    
    
 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
 
<%
    String ctxPath = request.getContextPath();
    // ctxPath ==> /JSPservletBegin
%>
 
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>개인성향 모든 정보 출력 페이지</title>
 
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> 
 
 
<%--bootstrap CSS --%>
<link rel="stylesheet" href="<%= ctxPath%>/bootstrap-4.6.0-dist/css/bootstrap.min.css" type="text/css"> 
 
 
<style type="text/css">
 
    div#div1, div#div2 {
        /* border : solid 1px gray; */
        width:80%;
        margin: 20px auto;
    }
    
    div#div1 >table {
        width : 100%;
        border-collapse : collaspse;
        
    }
 
    div#div1 >table th, div#div1 >table td {
        border: solid 1px gray;
    }
    
    div#div1 >table >tbody > tr:hover {
        background-color : blue;
        color : white;
        cursor :pointer;
    }
    
    tbody > tr > td:first-child > span {
        /* color : blue; */
        display : none;
    
    }
 
</style>
 
<script type="text/javascript" src="<%= ctxPath%>/js/jquery-3.6.0.min.js"></script>
<script type="text/javascript" src="<%= ctxPath%>/bootstrap-4.6.0-dist/js/bootstrap.bundle.min.js"></script> 
 
<script type="text/javascript">
 
    $(document).ready(function(){
        
        $("tbody > tr").click( (e)=>{
            //alter("헤헤헤");
            
        const $target = $(e.target); //<td>태그이다. td태그 누른곳 
        //console.log("확인용 $target.html() => " + $target.html());
        
        
        const seq = $target.parent().find("span").text(); //클린한곳 td 에서 올라가서 tr에서 sapn태그찾아서 그 text가 시퀀스이다.
        //console.log("확인용 seq => " + seq);
        
        //다음페이지로 넘겨준다
        location.href="personDetail.do?seq="+seq;
 
        
        });
        
    });
</script>
</head>
<body>
    
    <div id="div1">
        <h3>개인성향 모든 정보 출력 페이지(스크립틀릿을 사용하여 작성한 것)</h3>    
<%
    //                                 형변환
    List<PersonDTO_02> personList = (List<PersonDTO_02>) request.getAttribute("personList");
 
    if(personList.size( ) > 0) { %>
        <table>
            <thead>
                <tr>
                    <th>성명</th>
                    <th>학력</th>
                    <th>색상</th>
                    <th>음식</th>
                    <th>등록일자</th>
                </tr>    
            </thead>
            
            <tbody>
        <%
            for( PersonDTO_02 psdto : personList) {
        %>        
                <tr>
                    <td><span><%=psdto.getSeq()%></span><%= psdto.getName() %></td>
                    <td><%= psdto.getSchool() %></td>
                    <td><%= psdto.getColor() %></td>
                    <td><%= psdto.getstrFood() %></td>
                    <td><%= psdto.getRegisterday()%></td>
                
                </tr>
        <%        
            }
        %>
            </tbody>
        
        </table>
<%     
    }
    
    else { %>
        <span style="color:red;">데이터가 존재하지 않습니다.</span>
<% 
    }
%>    
    
    
    </div>    
    
    <div id="div2">
    
        <hr style="border : solid 1px red; margin:40px 0;">
    
        <div class="container-fluid">
            <h3>개인성향 모든 정보 출력 페이지(JSTL을 사용하여 작성한 것)</h3>
    
            <c:if test="${not empty requestScope.personList}" >
 
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>성명</th>
                            <th>학력</th>
                            <th>색상</th>
                            <th>음식</th>
                            <th>등록일자</th>
                        </tr>    
                    </thead>
                    
                    <tbody>
                        <c:forEach var="psdto" items="${requestScope.personList}">
                            <tr>
                                <td><span>${psdto.seq}</span>${psdto.name}</td> <%--psdto.get key 값인거다 앞글자 소문자 dto에서 가져오는거 --%>
                                <td>${psdto.school}</td>
                                <td>${psdto.color}</td>
                                <td>${psdto.strFood}</td>
                                <td>${psdto.registerday}</td>    
                            </tr>
                        </c:forEach>
                    </tbody>
                
                <c:if test="${empty requestScope.personList}" >
                    <span style="color:red;">데이터가 존재하지 않습니다.</span>
                
                </c:if>
                
                </table>
            
            </c:if>
            
        </div>
        
        <p class="text-center mt-5">
            <button type="button" class="btn btn-info" onclick="javascript:location.href='personRegister.do'">개인성향 입력페이지로 가기</button>
        </p>
        
    </div>
    
    
    
    
 
</body>
</html>
cs

 

<실패시>

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h2 style="color : red;">장애발생으로 인해 회원조회 실패!!</h2>
 
</body>
</html>
cs

 

 

 

2. 서블릿 만들어주기 (새로운 서블릿) <PersonSelect_06>  : 2번 4번

"/personSelect.do" URL 맵핑해주기

 

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
package chap05.oracle;
 
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
 
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
 
@WebServlet("/personSelect.do")
public class PersonSelect_06 extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    InterPersonDAO_03 dao = new PersonDAO_04();
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //url만 바뀌면 get방식이다 method에 아무것도 안쓰면 get
        
        // tbl_person_interest 테이블에 저장되어진 행(데이터)을 읽어다가(select) 웹페이지에 보여주어야 한다.
        
        //다시시작 4번 dao에서 던져준 오류처리를 포함해 db에서 불러오기(Dao) 성공,실패시 넘어가는 veiw단 페이지로 forward 해주기         
        String path ="";
        try {
             List<PersonDTO_02> personList = dao.selectAll();
             request.setAttribute("personList", personList);//select해온거 저장소에 저장해주기 
             
             path ="/WEB-INF/chap_right/personSelectAll.jsp"//성공페이지
        } catch (SQLException e) {
            e.printStackTrace();            
            path ="/WEB-INF/chap_right/personSelectAll_fail.jsp";
        }
        
        RequestDispatcher dispatcher = request.getRequestDispatcher(path);
        dispatcher.forward(request, response);
    }
 
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
        doGet(request, response);
        //form태그에서 전송할때 post 써주어야 post방식
    }
 
}
 
cs

 

 

 

3.interDao Dao : 3번

 

<interDAO>  테이블에 저장되어진 모든 행들을 select 해주는 추상메소드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package chap05.oracle;
 
import java.sql.SQLException;
import java.util.List;
 
public interface InterPersonDAO_03 {
    
    //개인성향을 입력(insert)해주는 추상메소드(미완성메소드)
    int personRegister(PersonDTO_02 psdto) throws SQLException;
    //파라미터 DTO 데이터필요하니까 DTO 넣어준다
    
    // tbl_person_interest 테이블에 저장되어진 모든 행들을 select 해주는 추상메소드(미완성메소드)         
    List<PersonDTO_02> selectAll() throws SQLException;
    //제네릭 PersonDTO_02 , 모두긁어오니까 파라미터필요없다
    
    
    
    
}
 
 
cs

 

 

<DAO>

 

 

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
//다시시작 3번
    // tbl_person_interest 테이블에 저장되어진 모든 행들을 select 해주는 메소드
    @Override
    public List<PersonDTO_02> selectAll() throws SQLException {
        
        //리턴타입은 List<PersonDTO_02> 
        List<PersonDTO_02> personList = new ArrayList<>();
        
        try {
            //싱클톤 패턴기법
            conn = MyDBConnection_05.getConn();
            
            //db에서 java로변환해왔음 
            String sql = " select seq, name, school, color, food, to_char(registerday, 'yyyy-mm-dd hh24:mi:ss') AS registerday "
                    + " from tbl_person_interest "
                    + " order by seq ";
            
            //sql 전달할 우편배달부
            pstmt = conn.prepareStatement(sql);    
            
            rs = pstmt.executeQuery();
            
            while(rs.next()) {
                
                PersonDTO_02 psdto = new PersonDTO_02();
                psdto.setSeq(rs.getInt(1)); // 또는 psdto.setSeq(rs.getInt("SEQ")); 컬럼명
                psdto.setName(rs.getString(2)); // 또는 psdto.setSeq(rs.getInt("name")); 컬럼명
                psdto.setSchool(rs.getString(3));
                psdto.setColor(rs.getString(4));
                
                String food = rs.getString(5); //rs.getString("FOOD");
                
                
                if(food != null) { //food가 null 아닐때
                    psdto.setFood(food.split("\\,")); //{"짜장면","탕수육","팔보채"}
                    
                }
                else {
                    psdto.setFood(null);
                }
                
                psdto.setRegisterday(rs.getString(6));
                
                
                personList.add(psdto); // list에 추가
                
                
            }// end of while(rs.next())--------------
            
 
            }finally {
                close(); // 자원반납        
            }
        
        return personList;
        
    }// end of public List<PersonDTO_02> selectAll() throws SQLException
cs

 

4. 성공,실패시 보여줄 view 단 jsp 만들기 / 다음페이지로 이동 :5번

personSelectAll.jsp ==> personDetail.jsp
"personSelect.do"   ==> "personDetail.do?seq="+seq;

 

<p class="text-center mt-5">
<button type="button" class="btn btn-info" onclick="javascript:location.href='personRegister.do'">개인성향 입력페이지로 가기</button>
</p>
        

 

 

 

re시작
1.정보 눌렀을때 보여주는 veiw 단 jsp  "personDetail.do?seq="+seq;< >

2.보여줄 페이지와 맵핑할 07 서블릿 만들어주기 (새로운 서블릿) <PersonDetail_07>


다음포스팅에서 계속