'Back-End/JSP'에 해당되는 글 71건

  1. 2019.05.26 jsp model 2 게시판 정리
  2. 2019.05.26 19.05.26 jsp 게시판 게시글 삭제 (model 2 동영상 21강)
  3. 2019.05.26 19.05.26 jsp 게시판 게시글 수정 (model 2 동영상 19강~20강)
  4. 2019.05.26 19.05.26 jsp 게시판 답글 작성 (model 2 동영상 18강)
  5. 2019.05.25 19.05.25 jsp 게시판 내용 확인 (model 2 동영상 17강)
  6. 2019.05.25 19.05.25 jsp 게시판 쓰기 (model 2 동영상 16강)
  7. 2019.05.25 19.05.25 jsp 게시판 보기 (model 2 동영상 15강)
  8. 2019.05.24 19.05.24 게시판 보기 (model 2 동영상 12강~14강)

jsp model 2 게시판 정리

Back-End/JSP 2019. 5. 26. 20:46

model 2 게시판 코드 목록






 분류

 파일 이름

 기능

JSP 파일

BoardList.jsp 

게시글 리스트 

BoardWriteForm.jsp

게시글 작성

BoardInfo.jsp

게시글 1개의 정보

BoardDeleteForm.jsp

게시글 삭제

BoardUpdateForm.jsp 

게시글 수정

 BoardReWriteForm.jsp

 게시글 답글 

Bean 클래스

 BoardBean.java

빈 클래스

 DAO (DB연결) 클래스

 BoardDAO.java

DB연결 

 서블릿 파일

BoardListCon.java

게시글 리스트 연결 서블릿 

  BoardWriteProcCon.java

글쓰기 처리 서블릿 

 BoardInfoControl.java

 게시글 1개 정보 처리 서블릿

 BoardDeleteCon.java

 게시글 삭제 서블릿

BoardDeleteProcCon.java 

 게시글 삭제 처리 서블릿

BoardUpdateCon.java 

 게시글 수정 서블릿

BoardUpdateProcCon.java

 게시글 수정 처리 서블릿

BoardReWriteCon.java

답글 작성 서블릿 

BoardReWriteProcCon.java

답글 작성 처리 서블릿 



BoardList.jsp (게시글 리스트)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<!-- 게시글 수정시에 비밀번호가 맞으면 확인메시지 출력 -->
<c:if test="${msg == '수정이 완료되었습니다.' }">
    <script type="text/javascript">
        alert("게시글이 수정되었습니다.");
    </script>
</c:if>
 
<!-- 게시글 수정시에 비밀번호가 틀렸을시 경고창 출력 -->
<c:if test="${msg == '비밀번호가 틀렸습니다.' }">
    <script type="text/javascript">
        alert("비밀번호가 틀렸습니다.");
    </script>
</c:if>
 
<c:if test="${msg == 2 }">
    <script type="text/javascript">
        alert("삭제시 비밀번호가 틀렸습니다.");
    </script>
</c:if>
 
<body>
    <center>
        <h2>전체 게시글 보기</h2>
        <table width="700" border="1" bordercolor="skyblue">
            <tr height="40">
                <td colspan="5" align="right">
                    <button onclick="location.href='BoardWriteForm.jsp'">글쓰기</button>
                </td>
            </tr>
 
            <tr height="40">
                <td width="50" align="center">번호</td>
                <td width="320" align="center">제목</td>
                <td width="100" align="center">작성자</td>
                <td width="150" align="center">작성일</td>
                <td width="80" align="center">조회수</td>
            </tr>
            <!-- $안에 number을 사용하면 계속 number만 출력되기 때문에 forEach문으로 number을 계속 1씩 감소시켜야 한다. -->
            <c:set var="number" value="${number}" />
            <c:forEach var="bean" items="${v}">
 
 
                <tr height="40">
                    <td width="50" align="left">${number }</td>
                    <td width="50" align="left">
                        <!-- 들여쓰기 구문 --> <!-- 첫번째 (1) 은 들여쓰기할 필요가 없다. --> <!-- 공백을 여러개 출력하기 위한 구문 -->
                        <c:if test="${bean.re_step > 1 }">
                            <c:forEach var="j" begin="1" end="${(bean.re_step-1)*5}">
                &nbsp;
            </c:forEach>
                        </c:if<!-- 버튼을 눌렀을때 실행이 되게끔 a태그를 건다 --> <a
                        href="BoardInfoControl.do?num=${bean.num }">${bean.subject } </a>
 
                    </td>
                    <td width="50" align="left">${bean.writer }</td>
                    <td width="50" align="left">${bean.reg_date }</td>
                    <td width="50" align="left">${bean.readcount }</td>
                </tr>
                <c:set var="number" value="${number-1 }" />
            </c:forEach>
        </table>
        <p>
            <!-- 페이지 카운터링 소스를 작성한다 -->
            <c:if test="${count > 0 }">
                <c:set var="pageCount"
                    value="${count / pageSize +(count%pageSize == 0 ? 0: 1)}" />
                <c:set var="startPage" value="${1 }" />
 
                <c:if test="${currentPage %10 != 0 }">
                    <!-- 인트타입으로 변환하기 위해 포장클래스인 integer을 사용한다. -->
                    <!-- 결과를 정수형으로 리턴받아야 하기에 fmt태그를 사용
        fmt는 코어태그가 아니기 때문에 위쪽에서 태그라이브러리를 추가해야한다.-->
                    <fmt:parseNumber var="result" value="${currentPage/10 }"
                        integerOnly="true" />
                    <c:set var="startPage" value="${result*10+1 }" />
                </c:if>
 
                <!-- c:if문은 else를 사용할 수 없기 때문에 이번에는  currentPage %10 == 0 이라는 값을 넣어주어야 한다.-->
 
                <c:if test="${currentPage %10 == 0 }">
                    <!-- 인트타입으로 변환하기 위해 포장클래스인 integer을 사용한다. -->
                    <!-- 결과를 정수형으로 리턴받아야 하기에 fmt태그를 사용
        fmt는 코어태그가 아니기 때문에 위쪽에서 태그라이브러리를 추가해야한다.-->
                    <c:set var="startPage" value="${(result-1)*10+1 }" />
                </c:if>
 
                <!-- 화면에 보여질 페이지 처리 숫자를 표현 -->
                <c:set var="pageBlock" value="${10 }" />
                <c:set var="endPage" value="${startPage+pageBlock-1 }" />
                <c:if test="${endPage > pageCount }">
                    <c:set var="endPage" value="${pageCount }" />
                </c:if>
 
                <!-- 10보다 페이지가 크면 "이전" 이라는 링크를 걸지 파악하는 구문 (if)-->
                <c:if test="${startPage > 10 }">
                    <a href='BoardListCon.do?pageNum=${startPage-10 }'>[이전]</a>
                </c:if>
 
                <!-- 페이징 처리 -->
                <c:forEach var="i" begin="${startPage }" end="${endPage }">
                    <a href='BoardListCon.do?pageNum=${i}'>[${i}]</a>
                </c:forEach>
 
                <!-- 다음 -->
                <c:if test="${endPage<pageCount}">
                    <a href='BoardListCon.do?pageNum=${startPage+10 }'>[다음]</a>
                </c:if>
            </c:if>
    </center>
</body>
</html>
 
cs



BoardWriteForm.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
<%@ 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>
        <h2>게시글 쓰기</h2>
        <!-- 컨트롤러가 읽어들이게끔 페이지 이동시킴 -->
        <form action="BoardWriteProcCon.do" method="post">
            <table width="600" border="1" bordercolor="gray" bgcolor="skyblue">
                <!-- bordercolor는 선색깔 지정 -->
                <tr height="40">
                    <td align="center" width="150">작성자</td>
                    <!-- ref는 데이터베이스에서 처리하기 때문에 따로 받지 않는다. -->
                    <td width="450"><input type="text" name="writer" size="60"></td>
                </tr>
 
                <tr height="40">
                    <td align="center" width="150">제목</td>
                    <td width="450"><input type="text" name="subject" size="60"></td>
                </tr>
 
                <tr height="40">
                    <td align="center" width="150">이메일</td>
                    <td width="450"><input type="text" name="email" size="60"></td>
                </tr>
 
                <tr height="40">
                    <td align="center" width="150">비밀번호</td>
                    <td width="450"><input type="password" name="password"
                        size="61"></td>
                </tr>
 
                <tr height="40">
                    <td align="center" width="150">글내용</td>
                    <td width="450"><textarea rows="10" cols="50" name="content"></textarea></td>
                </tr>
 
                <tr height="40">
                    <td align="center" colspan="2"><input type="submit"
                        value="글쓰기"> &nbsp;&nbsp; <input type="reset" value="다시작성">
                        &nbsp;&nbsp;
                        <button onclick="location.href='BoardListCon.do'">전체 게시글
                            보기</button<!-- 클릭하면 BoardList.jsp페이지로 넘어가는 버튼--></td>
                </tr>
            </table>
        </form>
    </center>
</body>
</html>
 
cs



BoardInfo.jsp (게시글 1개의 정보)

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>
    <center>
        <h2>게시글 보기</h2>
 
        <table width="600" border="1">
            <tr height="40">
                <td align="center" width="120">글 번호</td>
                <td align="center" width="180">${bean.num }</td>
                <td align="center" width="120">조회수</td>
                <td align="center" width="180">${bean.readcount }</td>
            </tr>
 
            <tr height="40">
                <td align="center" width="120">작성자</td>
                <td align="center" width="180">${bean.writer }</td>
                <td align="center" width="120">작성일</td>
                <td align="center" width="180">${bean.reg_date}</td>
            </tr>
 
            <tr height="40">
                <td align="center" width="120" colspan="2">이메일</td>
                <td align="center" width="180" colspan="2">${bean.email }</td>
            </tr>
 
            <tr height="40">
                <td align="center" width="120">제목</td>
                <td align="center" colspan="3">${bean.subject }</td>
            </tr>
 
            <tr height="80">
                <td align="center" width="120">글 내용</td>
                <td align="center" colspan="3">${bean.content }</td>
            </tr>
 
 
            <!-- 답글쓰기는 게시글 번호 그룹등을 다 넘겨주어야 한다. 게시글의 번호가 바뀌기 때문 -->
            <tr height="40">
                <td align="center" colspan="4"><input type="button"
                    value="답글쓰기"
                    onclick="location.href='BoardReWriteCon.do?num=${bean.num }&ref=${bean.ref }&re_step=${bean.re_step }&re_level=${bean.re_level }'">
                    <!-- 부모글의 ref, revel, num값을 다 알고 있어야된다.(리플달기이기 때문) --> <!-- 위에처럼 num값만 넘겨서 할수도 있다.
        int num = Integer.parseInt(request.getParameter("num").trim());
        BoardDAO bdao = new BoardDAO();
        BoardBean bean = bdao.getOneBoard(num); --> <input type="button"
                    value="수정하기"
                    onclick="location.href = 'BoardUpdateCon.do?num=${bean.num}'">
                    <input type="button" value="삭제하기"
                    onclick="location.href = 'BoardDeleteCon.do?num=${bean.num }'">
                    <input type="button" value="목록보기"
                    onclick="location.href = 'BoardListCon.do'">
        </table>
    </center>
 
 
 
 
 
</body>
</html>
cs



BoardDeleteForm.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
<%@ 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>
        <h2>게시글 삭제</h2>
 
        <form action="BoardDeleteProcCon.do" method="post">
            <table width="600" border="1">
 
 
                <tr height="40">
                    <td width="200" align="center">패스워드</td>
                    <td width="400">&nbsp; <input type="password" name="password"
                        size="60"></td>
                </tr>
 
                <tr height="40">
                    <td colspan="4" align="center"><input type="hidden" name="num"
                        value="${bean.num }"<!-- 패스워드를 히든으로 넘기면 한번더 db에 연결할 필요 없이 바로 패스워드가 맞는지 틀리는지 확인할 수 있다. -->
                        <input type="hidden" name="pass" value="${bean.password }">
 
                        <input type="submit" value="글삭제"> &nbsp;&nbsp; <input
                        type="button" onclick="location.href='BoardListCon.do'"
                        value="전체글보기"></td>
                </tr>
            </table>
        </form>
    </center>
</body>
</html>
cs



BoardUpdateForm.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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
    <center>
        <h2>게시글 수정</h2>
 
        <form action="BoardUpdateProcCon.do" method="post">
            <table width="600" border="1">
                <tr height="40">
 
                    <td width="160" align="center">작성자</td>
                    <td width="60" align="center">${bean.writer }</td>
 
                    <td width="160" align="center">작성일</td>
                    <td width="220" align="center">${bean.reg_date }</td>
                </tr>
 
                <tr height="40">
                    <td width="170" align="center">제목</td>
                    <td width="430" colspan="3">&nbsp; <input type="text"
                        name="subject" value="${bean.subject }" size="60"></td>
                </tr>
 
                <tr height="40">
                    <td width="200" align="center">패스워드</td>
                    <td width="400">&nbsp; <input type="password" name="password"
                        size="30"></td>
                </tr>
 
                <tr height="40">
                    <td width="170" align="center">글내용</td>
                    <td width="430" colspan="3"><textarea rows="10" cols="60"
                            name="content" align="left">${bean.content }</textarea></td>
                </tr>
 
                <tr height="40">
                    <td colspan="4" align="center"><input type="hidden" name="num"
                        value="${bean.num }"<!-- 패스워드를 히든으로 넘기면 한번더 db에 연결할 필요 없이 바로 패스워드가 맞는지 틀리는지 확인할 수 있다. -->
                        <input type="hidden" name="pass" value="${bean.password }">
                        <input type="submit" value="글수정"> &nbsp;&nbsp; <input
                        type="button" onclick="location.href='BoardListCon.do'"
                        value="전체글보기"></td>
                </tr>
            </table>
        </form>
    </center>
</body>
</html>
cs



BoardReWriteForm.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
<%@ 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>
        <h2>답변글 입력하기</h2>
 
        <form action="BoardReWriteProcCon.do" method="post">
            <!-- 답변글 처리 페이지로 자료를 전달 -->
            <table width="600" border="1" bordercolor="gray" bgcolor="skyblue">
 
                <tr height="40">
                    <td width="150" align="center">작성자</td>
                    <td width="450"><input type="text" name="writer" size="60"></td>
                </tr>
 
                <tr height="40">
                    <td width="150" align="center">제목</td>
                    <td width="450"><input type="text" name="subject" value="[답변]"
                        size="60"></td>
                </tr>
 
                <tr height="40">
                    <td width="150" align="center">이메일</td>
                    <td width="450"><input type="email" name="email" size="60"></td>
                </tr>
 
                <tr height="40">
                    <td width="150" align="center">비밀번호</td>
                    <td width="450"><input type="password" name="password"
                        size="60"></td>
                </tr>
 
                <tr height="40">
                    <td width="150" align="center">글내용</td>
                    <td width="450"><textarea rows="10" cols="60" name="content"></textarea></td>
                </tr>
                <!-- form에서 사용자로부터 입력 받지 않고 데이터를 넘김 -->
                <tr height="40">
                    <!-- 각 데이터에 맞는 버튼을 만들어준다. -->
                    <td align="center" colspan="2"><input type="hidden" name="ref"
                        value="${ref }"> <input type="hidden" name="re_step"
                        value="${re_step }"> <input type="hidden" name="re_level"
                        value="${re_level }"> <input type="submit" value="답글쓰기완료">
                        &nbsp;&nbsp; <input type="reset" value="취소"> &nbsp;&nbsp;
                        <input type="button" onclick="location.href='BoardListCon.do'"
                        value="전체글보기"></td>
                    <!-- 리스트 화면으로 돌아가는 버튼 -->
                </tr>
 
            </table>
        </form>
    </center>
</body>
</html>
cs



BoardBean.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
98
99
100
101
102
103
104
105
106
package model;
 
public class BoardBean { // 빈클래스 생성
 
    private int num;
    private String email;
    private String subject;
    private String password;
    private String reg_date;
    private String writer;
    private int ref;
    private int re_step;
    private int re_level;
    private int readcount;
    private String content;
 
    public int getNum() {
        return num;
    }
 
    public void setNum(int num) {
        this.num = num;
    }
 
    public String getEmail() {
        return email;
    }
 
    public void setEmail(String email) {
        this.email = email;
    }
 
    public String getSubject() {
        return subject;
    }
 
    public void setSubject(String subject) {
        this.subject = subject;
    }
 
    public String getPassword() {
        return password;
    }
 
    public void setPassword(String password) {
        this.password = password;
    }
 
    public String getReg_date() {
        return reg_date;
    }
 
    public void setReg_date(String reg_date) {
        this.reg_date = reg_date;
    }
 
    public String getWriter() {
        return writer;
    }
 
    public void setWriter(String writer) {
        this.writer = writer;
    }
 
    public int getRef() {
        return ref;
    }
 
    public void setRef(int ref) {
        this.ref = ref;
    }
 
    public int getRe_step() {
        return re_step;
    }
 
    public void setRe_step(int re_step) {
        this.re_step = re_step;
    }
 
    public int getRe_level() {
        return re_level;
    }
 
    public void setRe_level(int re_level) {
        this.re_level = re_level;
    }
 
    public int getReadcount() {
        return readcount;
    }
 
    public void setReadcount(int readcount) {
        this.readcount = readcount;
    }
 
    public String getContent() {
        return content;
    }
 
    public void setContent(String content) {
        this.content = content;
    }
 
}
 
cs



BoardDAO.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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
package model;
 
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 BoardDAO {
 
    Connection con;
    PreparedStatement pstmt;
    ResultSet rs;
 
    // 데이터 베이스에 연결 메소드
    public void getCon() {
        try {
            Context initctx = new InitialContext();
            Context envctx = (Context) initctx.lookup("java:comp/env");
            // 타입이 데이터 소스이므로 데이터소스로 (타입변환해서) 받는다.
            DataSource ds = (DataSource) envctx.lookup("jdbc/pool");
            // 얻은 데이터소스를 사용해 연결한다.
            con = ds.getConnection(); // 커넥션 연결 해주는 메소드
 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    // 전체 게시글의 갯수를 리턴하는 메소드
    public int getAllCount() {
        getCon();
        // 개시글의 갯수를 세야하기 때문에 카운트 변수를 추가하고 초기값을 선언한다.
        int count = 0;
 
        try {
            // sql 쿼리 준비함
            String sql = "select count(*) from board";
            pstmt = con.prepareStatement(sql);
            // ?표가 없으므로 바로 결과실행후 리턴시켜주면 된다.
            rs = pstmt.executeQuery();
            // 전체게시글은 한칸에서 밖에 출력이 되지 않으므로 1칸만 있으면 된다. 반복문 말고 if문으로 사용한다.
            if (rs.next()) { // 데이터가 있다면 카운트에 넣는다.
                // 전체 게시글 수
                count = rs.getInt(1);
            }
            con.close();
 
        } catch (Exception e) {
            e.printStackTrace();
        }
        return count;
    }
 
    // 화면에 보여질 데이터를 10개씩 추출해서 리턴하는 메소드
    public Vector<BoardBean> getAllBoard(int startRow, int endRow) {
        // 리턴할객체 선언
        getCon();
        Vector<BoardBean> v = new Vector<>();
        try {
            // 쿼리 작성
            String sql = "select * from (select A.*, Rownum Rnum from (select * from board order by ref desc, re_step asc)A)"
                    + "where Rnum >= ? and Rnum <= ?";
            // 쿼리 실행할 객체를 선언
            pstmt = con.prepareStatement(sql);
            pstmt.setInt(1, startRow);
            pstmt.setInt(2, endRow);
            // 쿼리실행후 결과 저장
            rs = pstmt.executeQuery();
            // 데이터 개수가 몇개인지 모르기에 반복문을 이용하여 데이터를 추출
            while (rs.next()) {
                // 데이터를 패키징 ( BoardBean 클래스를 이용) 해줌
                BoardBean bean = new BoardBean();
                bean.setNum(rs.getInt(1));
                bean.setWriter(rs.getString(2));
                bean.setEmail(rs.getString(3));
                bean.setSubject(rs.getString(4));
                bean.setPassword(rs.getString(5));
                bean.setReg_date(rs.getDate(6).toString());
                bean.setRef(rs.getInt(7));
                bean.setRe_step(rs.getInt(8));
                bean.setRe_level(rs.getInt(9));
                bean.setReadcount(rs.getInt(10));
                bean.setContent(rs.getString(11));
                // 패키징한 데이터를 벡터에 저장
                v.add(bean);
            }
            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return v;
    }
 
    // 하나의 게시글을 저장하는 메소드 호출
    public void insertBoard(BoardBean bean) {
 
        getCon();
        // 초기값 지정
        int ref = 0;
        int re_step = 1;// 새글이기에
        int re_level = 1;// 새글이기에
 
        try {
            // 쿼리 작성
            // 이 sql에서 1만 더하면 되기때문에 가장큰값을 검색
            String refsql = "select max(ref) from board";
            pstmt = con.prepareStatement(refsql);
            // 쿼리 실행후 결과를 리턴
            rs = pstmt.executeQuery();
            if (rs.next()) {
                ref = rs.getInt(1+ 1// ref가장 큰 값에 1을 더해줌
                // 최신글은 글번호가 가장 크기 때문에 원래 있던 글에서 1을 더해줌
 
            }
            // 데이터를 삽입하는 쿼리
            String sql = "insert into board values(board_seq.NEXTVAL,?,?,?,?,sysdate,?,?,?,0,?)";
            pstmt = con.prepareStatement(sql);
            // ?에 값을 매핑한다.
            pstmt.setString(1, bean.getWriter());
            pstmt.setString(2, bean.getEmail());
            pstmt.setString(3, bean.getSubject());
            pstmt.setString(4, bean.getPassword());
            pstmt.setInt(5, ref);
            pstmt.setInt(6, re_step);
            pstmt.setInt(7, re_level);
            pstmt.setString(8, bean.getContent());
 
            pstmt.executeUpdate();
            con.close();
 
        } catch (Exception e) {
            e.printStackTrace();
        }
 
    }
 
    // 하나의 게시글을 읽어들이는 메소드 작성
    // 게시글을 읽었다는 뜻은 조회수가 1증가된다는 뜻
    // 게시글을 누르면 조회수도 올라가야함
    public BoardBean getOneBoard(int num) {
        getCon();
        // 초기값이니까 null을 준다.
        BoardBean bean = null;
        try {
            // 하나의 게시글을 읽었을때 조회수 증가
            String countsql = "update board set readcount = readcount+1 where num=?";
            pstmt = con.prepareStatement(countsql);
            pstmt.setInt(1, num);
            // 쿼리를 실행
            pstmt.executeUpdate();
 
            // 한 게시글에 대한 정보를 리턴해주는 쿼리를 작성
            String sql = "select * from board where num=?";
            pstmt = con.prepareStatement(sql);
            // ?에 값을 집어넣기
            pstmt.setInt(1, num);
            // 쿼리실행후 결과를 리턴
            rs = pstmt.executeQuery();
            if (rs.next()) {
                bean = new BoardBean();
                bean.setNum(rs.getInt(1));
                bean.setWriter(rs.getString(2));
                bean.setEmail(rs.getString(3));
                bean.setSubject(rs.getString(4));
                bean.setPassword(rs.getString(5));
                bean.setReg_date(rs.getDate(6).toString());
                bean.setRef(rs.getInt(7));
                bean.setRe_step(rs.getInt(8));
                bean.setRe_level(rs.getInt(9));
                bean.setReadcount(rs.getInt(10));
                bean.setContent(rs.getString(11));
 
            }
 
            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bean;
 
    }
 
    // 답변글을 저장하는 메소드
    public void reInsertBoard(BoardBean bean) {
        getCon();
        // 초기값 지정
        int ref = bean.getRef();
        int re_step = bean.getRe_step();
        int re_level = bean.getRe_level();
 
        try {
            // 쿼리 작성
            // 이 sql에서 1만 더하면 되기때문에 가장큰값을 검색
            // 답변형 게시판의 특징인 글을 쓰면 먼저쓴글이 가장 위로 올라가야 하기 때문에 다른글들은 다 밑으로 내려야한다.
            String relevelsql = "update board set re_level=re_level+1 where ref=? and re_level >?";
            pstmt = con.prepareStatement(relevelsql);
            pstmt.setInt(1, ref);
            pstmt.setInt(2, re_level);
 
            // 쿼리 실행후 결과를 리턴
            pstmt.executeUpdate();
 
            // 데이터를 삽입하는 쿼리
            String sql = "insert into board values(board_seq.NEXTVAL,?,?,?,?,sysdate,?,?,?,0,?)";
            pstmt = con.prepareStatement(sql);
            // ?에 값을 매핑한다.
            pstmt.setString(1, bean.getWriter());
            pstmt.setString(2, bean.getEmail());
            pstmt.setString(3, bean.getSubject());
            pstmt.setString(4, bean.getPassword());
            pstmt.setInt(5, ref);
            pstmt.setInt(6, re_step + 1); // 기존 부모글에 스텝보다 1을 증가시켜야 한다.
            pstmt.setInt(7, re_level + 1); // 기존 부모글에 스텝보다 1을 증가시켜야 한다.
            pstmt.setString(8, bean.getContent());
 
            pstmt.executeUpdate();
            con.close();
 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    // 조회수를 증가하지 않는 하나의 게시글을 리턴하는 메소드
    // 게시글 확인을 확인하는 메소드에서 조회수 증가 쿼리만 제외한다.
    public BoardBean getOneUpdateBoard(int num) {
        getCon();
        // 초기값이니까 null을 준다.
        BoardBean bean = null;
        try {
 
            // 한 게시글에 대한 정보를 리턴해주는 쿼리를 작성
            String sql = "select * from board where num=?";
            pstmt = con.prepareStatement(sql);
            // ?에 값을 집어넣기
            pstmt.setInt(1, num);
            // 쿼리실행후 결과를 리턴
            rs = pstmt.executeQuery();
            if (rs.next()) {
                bean = new BoardBean();
                bean.setNum(rs.getInt(1));
                bean.setWriter(rs.getString(2));
                bean.setEmail(rs.getString(3));
                bean.setSubject(rs.getString(4));
                bean.setPassword(rs.getString(5));
                bean.setReg_date(rs.getDate(6).toString());
                bean.setRef(rs.getInt(7));
                bean.setRe_step(rs.getInt(8));
                bean.setRe_level(rs.getInt(9));
                bean.setReadcount(rs.getInt(10));
                bean.setContent(rs.getString(11));
 
            }
 
            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bean;
    }
 
    // 하나의 게시글을 수정하는 메소드
    public void updateBoard(int num, String subject, String content) {
 
        // 데이터베이스 연결
        getCon();
        try {
            String sql = "update board set subject=?,content=? where num=?";
            pstmt = con.prepareStatement(sql);
            // ?에 값을 대입한다.
            pstmt.setString(1, subject);
            pstmt.setString(2, content);
            pstmt.setInt(3, num);
 
            // 4. 쿼리를 실행한다.
            pstmt.executeUpdate();
            // insert, delete, update 쿼리 구문은 executeUpdate를 사용한다.
            // 즉 DML(데이터조작어)를 사용할 때는 executeUpdate()를 사용한다.
            // 5. 자원 반납
            con.close();
 
        } catch (Exception e) {
            e.printStackTrace();
        }
 
    }
 
    // 하나의 게시글을 삭제하는 메소드
    public void deleteBoard(int num) {
 
        getCon();
 
        try {
            String sql = "delete from board where num=?";
            pstmt = con.prepareStatement(sql);
            // ?에 값을 넣어준다.
            pstmt.setInt(1, num);
            pstmt.executeUpdate();
            con.close();
 
        } catch (Exception e) {
            e.printStackTrace();
        }
 
    }
}
cs



BoardListCon.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
package control;
 
import java.io.IOException;
import java.util.Vector;
 
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;
 
import model.BoardBean;
import model.BoardDAO;
 
/**
 * Servlet implementation class BoardListCon
 */
//웹 서블릿 url 설정
@WebServlet("/BoardListCon.do")
public class BoardListCon extends HttpServlet {
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        reqPro(request, response);
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        reqPro(request, response);
    }
 
    protected void reqPro(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // jsp쪽에서 출력되게끔 자료를 넘겨주어야 한다.
 
        // 화면에 보여질 게시글의 개수를 지정
        int pageSize = 10;
 
        // 현재 보여지고 있는 페이지의 넘버값을 읽어들인다.
        String pageNum = request.getParameter("pageNum");
 
        // null 처리
        if (pageNum == null) {
            pageNum = "1";
        }
        // 전체 게시글의 갯수
        int count = 0;
        // jsp 페이지 내에서 보여질 넘버링 숫자값을 저장하는 변수 선언
        int number = 0;
 
        // 현재 보여지고 있는 페이지 문자를 숫자로 변환
        int currentPage = Integer.parseInt(pageNum);
        // 전체 게시글의 갯수를 가져와야 하기에 데이터베이스 객체 생성
        BoardDAO bdao = new BoardDAO();
        count = bdao.getAllCount();
 
        // 현재 보여질 페이지 시작 번호를 설정
        int startRow = (currentPage - 1* pageSize + 1;
        int endRow = currentPage * pageSize;
 
        // 최신글 10개를 기준으로 게시글을 리턴 받아주는 메소드 호출
        Vector<BoardBean> v = bdao.getAllBoard(startRow, endRow);
        number = count - (currentPage - 1* pageSize;
 
        // 수정, 삭제시 비밀번호가 틀렸다면
        String msg = (String) request.getAttribute("msg");
 
        // BoardList.jsp 쪽으로 request 객체에 담아서 넘겨준다.
        request.setAttribute("v", v);
        request.setAttribute("number", number);
        request.setAttribute("pageSize", pageSize);
        request.setAttribute("count", count);
        request.setAttribute("currentPage", currentPage);
        request.setAttribute("msg", msg);
 
        // BoardList를 통해 forward를 시킨다.
        RequestDispatcher dis = request.getRequestDispatcher("BoardList.jsp");
        dis.forward(request, response);
 
    }
}
 
cs



BoardWriteProcCon.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
package control;
 
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;
 
import model.BoardBean;
import model.BoardDAO;
 
/**
 * Servlet implementation class BoardWriteProcCon
 */
// 글쓰기 처리 서블릿 선언
@WebServlet("/BoardWriteProcCon.do")
public class BoardWriteProcCon extends HttpServlet {
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        reqPro(request, response);
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        reqPro(request, response);
    }
 
    protected void reqPro(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("euc-kr");
        // 빈 클래스로 데이터를 읽어들인다.
        BoardBean bean = new BoardBean();
 
        // 5개의 값을 빈 클래스에 저장시킨다.
        bean.setWriter(request.getParameter("writer"));
        bean.setSubject(request.getParameter("subject"));
        bean.setEmail(request.getParameter("email"));
        bean.setPassword(request.getParameter("password"));
        bean.setContent(request.getParameter("content"));
 
        BoardDAO bdao = new BoardDAO();
        // insert메소드에 매개값으로 빈클래스가 가지고있는 값들을 넣어준다.
        bdao.insertBoard(bean);
 
        // BoardListCon.do로 request, response를 전달한다.
        RequestDispatcher dis = request.getRequestDispatcher("BoardListCon.do");
        dis.forward(request, response);
    }
}
 
cs



BoardInfoControl.java (게시글 1개 정보 처리 서블릿)

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 control;
 
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;
 
import model.BoardBean;
import model.BoardDAO;
 
//게시글 정보를 처리하는 서블릿
@WebServlet("/BoardInfoControl.do")
public class BoardInfoControl extends HttpServlet {
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        rePro(request, response);
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        rePro(request, response);
    }
 
    protected void rePro(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
 
        // num을 포장클래스를 이용해 타입변환을 시켜서 num에 넣는다. (게시글 번호)
        int num = Integer.parseInt(request.getParameter("num"));
 
        // 데이터베이스에 접근
        BoardDAO bdao = new BoardDAO();
        // 하나의 게시글에 대한 정보를 리턴
        BoardBean bean = bdao.getOneBoard(num);
 
        request.setAttribute("bean", bean);
 
        // view (jsp를 의미한다) 쪽으로 데이터를 넘겨준다.
        // BoardInfo.jsp로 request, response를 전달
        RequestDispatcher dis = request.getRequestDispatcher("BoardInfo.jsp");
        dis.forward(request, response);
 
    }
 
}
 
cs



BoardDeleteCon.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
package control;
 
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;
 
import model.BoardBean;
import model.BoardDAO;
 
/**
 * Servlet implementation class BoardDeleteCon
 */
@WebServlet("/BoardDeleteCon.do")
public class BoardDeleteCon extends HttpServlet {
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        reqPro(request, response);
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        reqPro(request, response);
    }
 
    protected void reqPro(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
 
        // 글삭제이기 때문에 글 번호 값을 입력받는다.
        int num = Integer.parseInt(request.getParameter("num"));
 
        // 데이터베이스에 접근하여 하나의 게시글을 리턴하는 메소드
        BoardDAO bdao = new BoardDAO();
 
        // 빈 클래스 타입으로 리턴
        BoardBean bean = bdao.getOneUpdateBoard(num); // 조회수를 증가시키지 않는 메소드를 사용함
 
        request.setAttribute("bean", bean);
 
        RequestDispatcher dis = request.getRequestDispatcher("BoardDeleteForm.jsp");
        dis.forward(request, response);
 
    }
}
 
cs



BoardDeleteProcCon.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
package control;
 
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;
 
import model.BoardDAO;
 
/**
 * Servlet implementation class BoardDeleteProcCon
 */
//게시글 삭제 처리 서블릿
@WebServlet("/BoardDeleteProcCon.do")
public class BoardDeleteProcCon extends HttpServlet {
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        reqPro(request, response);
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        reqPro(request, response);
    }
 
    protected void reqPro(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
 
        // 사용자로부터 넘어온 데이터 3개를 받아준다.
        int num = Integer.parseInt(request.getParameter("num"));
        String password = request.getParameter("password");
        String pass = request.getParameter("pass");
 
        // 패스워드가 같을 경우에는 데이터를 삭제하고 리스트화면을 보여준다.
        if (password.equals(pass)) {
 
            BoardDAO bdao = new BoardDAO();
            bdao.deleteBoard(num);
 
            RequestDispatcher dis = request.getRequestDispatcher("BoardListCon.do");
            dis.forward(request, response);
 
        } else {
 
            request.setAttribute("msg"2);
            RequestDispatcher dis = request.getRequestDispatcher("BoardListcon.do");
 
        }
 
    }
}
 
cs



BoardUpdateCon.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
package control;
 
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;
 
import model.BoardBean;
import model.BoardDAO;
 
/**
 * Servlet implementation class BoardUpdateCon
 */
@WebServlet("/BoardUpdateCon.do")
public class BoardUpdateCon extends HttpServlet {
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        reqPro(request, response);
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        reqPro(request, response);
    }
 
    protected void reqPro(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
 
        // 해당 게시글의 번호를 먼저 읽어들인다. 그래야 게시글을 수정할 수 있기 때문
        int num = Integer.parseInt(request.getParameter("num"));
 
        // 데이터베이스에서 하나의 게시글에 대한 정보를 리턴하는 메소드 호출
 
        BoardDAO bdao = new BoardDAO();
        BoardBean bean = bdao.getOneUpdateBoard(num);
 
        // request에 데이터를 담기
        request.setAttribute("bean", bean);
 
        RequestDispatcher dis = request.getRequestDispatcher("BoardUpdateForm.jsp");
        dis.forward(request, response);
 
    }
 
}
 
cs



BoardUpdateProcCon.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 control;
 
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;
 
import model.BoardDAO;
 
/**
 * Servlet implementation class BoardUpdateProcCon
 */
//게시글 수정 처리 서블릿
//게시글 수정할 때 비밀번호를 입력해서 비밀번호가 맞으면 게시글을 수정할 수 있다.
@WebServlet("/BoardUpdateProcCon.do")
public class BoardUpdateProcCon extends HttpServlet {
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        reqPro(request, response);
    }
 
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        reqPro(request, response);
    }
 
    protected void reqPro(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 한글 처리
        request.setCharacterEncoding("euc-kr");
 
        // 폼에서 넘어온 데이터를 받아줌
        // 비밀번호를 받아서 db에 저장된 비밀번호와 맞는지 확인해서
        // 게시글 수정 가능
        int num = Integer.parseInt(request.getParameter("num"));
        String password = request.getParameter("password"); // 사용자로부터 입력받은 패스워드
        String pass = request.getParameter("pass"); // 실제 데이터베이스에 저장되어 있는 패스워드 값
        String subject = request.getParameter("subject");
        String content = request.getParameter("content");
 
        // password값과 pass값을 비교해서 맞으면 게시글 수정하게함.
        if (password.equals(pass)) {// 패스워드가 같다면 데이터를 수정
 
            BoardDAO bdao = new BoardDAO();
            // 패스워드는 비교만 하면 되기 때문에 따로 넘기지는 않고, 나머지 자료만 넘김
            // 왜냐하면 글 수정할때는 패스워드를 바꾸는게 아니라 제목, 내용만 바뀌는 것이기 때문
            bdao.updateBoard(num, subject, content);
            // 수정이 완료되었을시에 실행하고 게시물 리스트 페이지로 이동시킨다.
            request.setAttribute("msg""수정이 완료되었습니다.");
            RequestDispatcher dis = request.getRequestDispatcher("BoardListCon.do");
            dis.forward(request, response);
        } else {
            // 비밀번호가 틀렸다면 이전 페이지로 이동하고 실행
            request.setAttribute("msg""비밀번호가 틀렸습니다.");
            RequestDispatcher dis = request.getRequestDispatcher("BoardListCon.do");
            dis.forward(request, response);
 
        }
    }
 
}
 
cs



BoardReWriteCon.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
package control;
 
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;
 
import model.BoardBean;
import model.BoardDAO;
 
/**
 * Servlet implementation class BoardWriteProcCon
 */
// 글쓰기 처리 서블릿 선언
@WebServlet("/BoardReWriteCon.do")
public class BoardReWriteCon extends HttpServlet {
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        reqPro(request, response);
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        reqPro(request, response);
    }
 
    protected void reqPro(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
 
        // 한글타입이 아니기 때문에 한글처리는 안해도됨
        // 답글쓰기 같은 경우는 시퀀스가 있기때문에 자동으로 부여되서
        // 궂이 num값을 받아서 할 필요가 없다
        // Integer.pareInt는 문자를 int형식으로 변환할때 사용
        int ref = Integer.parseInt(request.getParameter("ref"));
        int re_step = Integer.parseInt(request.getParameter("re_step"));
        int re_level = Integer.parseInt(request.getParameter("re_level"));
 
        // 글관련 정보들을 다른페이지로 넘겨주기 위해서 담아놓는다.
        request.setAttribute("ref", ref);
        request.setAttribute("re_step", re_step);
        request.setAttribute("re_level", re_level);
 
        // BoardReWriteForm.jsp파일에 request, response에 담아놓은 자료들을 넘겨준다.
        RequestDispatcher dis = request.getRequestDispatcher("BoardReWriteForm.jsp");
        dis.forward(request, response);
    }
}
cs



BoardReWriteProcCon.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
package control;
 
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;
 
import model.BoardBean;
import model.BoardDAO;
 
/**
 * Servlet implementation class BoardReWriteProcCon
 */
@WebServlet("/BoardReWriteProcCon.do")
public class BoardReWriteProcCon extends HttpServlet {
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        reqPro(request, response);
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        reqPro(request, response);
    }
 
    protected void reqPro(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 빈클래스안에 받아온 데이터를 저장
        BoardBean bean = new BoardBean();
 
        request.setCharacterEncoding("euc-kr");
 
        bean.setWriter(request.getParameter("writer"));
        bean.setSubject(request.getParameter("subject"));
        bean.setEmail(request.getParameter("email"));
        bean.setPassword(request.getParameter("password"));
        bean.setContent(request.getParameter("content"));
 
        bean.setRef(Integer.parseInt(request.getParameter("ref")));
        bean.setRe_step(Integer.parseInt(request.getParameter("re_step")));
        bean.setRe_level(Integer.parseInt(request.getParameter("re_level")));
 
        BoardDAO bdao = new BoardDAO();
        // DAO클래스에 Insert메서드에 빈을 매개변수로 넘겨준다.
        bdao.reInsertBoard(bean);
 
        RequestDispatcher dis = request.getRequestDispatcher("BoardListCon.do");
        dis.forward(request, response);
 
    }
}
 
cs



:

19.05.26 jsp 게시판 게시글 삭제 (model 2 동영상 21강)

Back-End/JSP 2019. 5. 26. 14:49

게시글 삭제 기능 구현




BoardDeleteForm.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
<%@ 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>
        <h2>게시글 삭제</h2>
 
        <form action="BoardDeleteProcCon.do" method="post">
            <table width="600" border="1">
 
 
                <tr height="40">
                    <td width="200" align="center">패스워드</td>
                    <td width="400">&nbsp; <input type="password" name="password"
                        size="60"></td>
                </tr>
 
                <tr height="40">
                    <td colspan="4" align="center"><input type="hidden" name="num"
                        value="${bean.num }"<!-- 패스워드를 히든으로 넘기면 한번더 db에 연결할 필요 없이 바로 패스워드가 맞는지 틀리는지 확인할 수 있다. -->
                        <input type="hidden" name="pass" value="${bean.password }">
 
                        <input type="submit" value="글삭제"> &nbsp;&nbsp; <input
                        type="button" onclick="location.href='BoardListCon.do'"
                        value="전체글보기"></td>
                </tr>
            </table>
        </form>
    </center>
</body>
</html>
cs



BoardDeleteCon.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
.package control;
 
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;
 
import model.BoardBean;
import model.BoardDAO;
 
/**
 * Servlet implementation class BoardDeleteCon
 */
@WebServlet("/BoardDeleteCon.do")
public class BoardDeleteCon extends HttpServlet {
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        reqPro(request, response);
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        reqPro(request, response);
    }
 
    protected void reqPro(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
 
        // 글삭제이기 때문에 글 번호 값을 입력받는다.
        int num = Integer.parseInt(request.getParameter("num"));
 
        // 데이터베이스에 접근하여 하나의 게시글을 리턴하는 메소드
        BoardDAO bdao = new BoardDAO();
 
        // 빈 클래스 타입으로 리턴
        BoardBean bean = bdao.getOneUpdateBoard(num); // 조회수를 증가시키지 않는 메소드를 사용함
 
        request.setAttribute("bean", bean);
 
        RequestDispatcher dis = request.getRequestDispatcher("BoardDeleteForm.jsp");
        dis.forward(request, response);
 
    }
}
 
cs



BoardDeleteProcCon.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
.package control;
 
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;
 
import model.BoardDAO;
 
/**
 * Servlet implementation class BoardDeleteProcCon
 */
//게시글 삭제 처리 서블릿
@WebServlet("/BoardDeleteProcCon.do")
public class BoardDeleteProcCon extends HttpServlet {
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        reqPro(request, response);
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        reqPro(request, response);
    }
 
    protected void reqPro(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
 
        // 사용자로부터 넘어온 데이터 3개를 받아준다.
        int num = Integer.parseInt(request.getParameter("num"));
        String password = request.getParameter("password");
        String pass = request.getParameter("pass");
 
        // 패스워드가 같을 경우에는 데이터를 삭제하고 리스트화면을 보여준다.
        if (password.equals(pass)) {
 
            BoardDAO bdao = new BoardDAO();
            bdao.deleteBoard(num);
 
            RequestDispatcher dis = request.getRequestDispatcher("BoardListCon.do");
            dis.forward(request, response);
 
        } else {
 
            request.setAttribute("msg"2);
            RequestDispatcher dis = request.getRequestDispatcher("BoardListcon.do");
 
        }
 
    }
}
 
cs



BoardDAO.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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
.package model;
 
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 BoardDAO {
 
    Connection con;
    PreparedStatement pstmt;
    ResultSet rs;
 
    // 데이터 베이스에 연결 메소드
    public void getCon() {
        try {
            Context initctx = new InitialContext();
            Context envctx = (Context) initctx.lookup("java:comp/env");
            // 타입이 데이터 소스이므로 데이터소스로 (타입변환해서) 받는다.
            DataSource ds = (DataSource) envctx.lookup("jdbc/pool");
            // 얻은 데이터소스를 사용해 연결한다.
            con = ds.getConnection(); // 커넥션 연결 해주는 메소드
 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    // 전체 게시글의 갯수를 리턴하는 메소드
    public int getAllCount() {
        getCon();
        // 개시글의 갯수를 세야하기 때문에 카운트 변수를 추가하고 초기값을 선언한다.
        int count = 0;
 
        try {
            // sql 쿼리 준비함
            String sql = "select count(*) from board";
            pstmt = con.prepareStatement(sql);
            // ?표가 없으므로 바로 결과실행후 리턴시켜주면 된다.
            rs = pstmt.executeQuery();
            // 전체게시글은 한칸에서 밖에 출력이 되지 않으므로 1칸만 있으면 된다. 반복문 말고 if문으로 사용한다.
            if (rs.next()) { // 데이터가 있다면 카운트에 넣는다.
                // 전체 게시글 수
                count = rs.getInt(1);
            }
            con.close();
 
        } catch (Exception e) {
            e.printStackTrace();
        }
        return count;
    }
 
    // 화면에 보여질 데이터를 10개씩 추출해서 리턴하는 메소드
    public Vector<BoardBean> getAllBoard(int startRow, int endRow) {
        // 리턴할객체 선언
        getCon();
        Vector<BoardBean> v = new Vector<>();
        try {
            // 쿼리 작성
            String sql = "select * from (select A.*, Rownum Rnum from (select * from board order by ref desc, re_step asc)A)"
                    + "where Rnum >= ? and Rnum <= ?";
            // 쿼리 실행할 객체를 선언
            pstmt = con.prepareStatement(sql);
            pstmt.setInt(1, startRow);
            pstmt.setInt(2, endRow);
            // 쿼리실행후 결과 저장
            rs = pstmt.executeQuery();
            // 데이터 개수가 몇개인지 모르기에 반복문을 이용하여 데이터를 추출
            while (rs.next()) {
                // 데이터를 패키징 ( BoardBean 클래스를 이용) 해줌
                BoardBean bean = new BoardBean();
                bean.setNum(rs.getInt(1));
                bean.setWriter(rs.getString(2));
                bean.setEmail(rs.getString(3));
                bean.setSubject(rs.getString(4));
                bean.setPassword(rs.getString(5));
                bean.setReg_date(rs.getDate(6).toString());
                bean.setRef(rs.getInt(7));
                bean.setRe_step(rs.getInt(8));
                bean.setRe_level(rs.getInt(9));
                bean.setReadcount(rs.getInt(10));
                bean.setContent(rs.getString(11));
                // 패키징한 데이터를 벡터에 저장
                v.add(bean);
            }
            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return v;
    }
 
    // 하나의 게시글을 저장하는 메소드 호출
    public void insertBoard(BoardBean bean) {
 
        getCon();
        // 초기값 지정
        int ref = 0;
        int re_step = 1;// 새글이기에
        int re_level = 1;// 새글이기에
 
        try {
            // 쿼리 작성
            // 이 sql에서 1만 더하면 되기때문에 가장큰값을 검색
            String refsql = "select max(ref) from board";
            pstmt = con.prepareStatement(refsql);
            // 쿼리 실행후 결과를 리턴
            rs = pstmt.executeQuery();
            if (rs.next()) {
                ref = rs.getInt(1+ 1// ref가장 큰 값에 1을 더해줌
                // 최신글은 글번호가 가장 크기 때문에 원래 있던 글에서 1을 더해줌
 
            }
            // 데이터를 삽입하는 쿼리
            String sql = "insert into board values(board_seq.NEXTVAL,?,?,?,?,sysdate,?,?,?,0,?)";
            pstmt = con.prepareStatement(sql);
            // ?에 값을 매핑한다.
            pstmt.setString(1, bean.getWriter());
            pstmt.setString(2, bean.getEmail());
            pstmt.setString(3, bean.getSubject());
            pstmt.setString(4, bean.getPassword());
            pstmt.setInt(5, ref);
            pstmt.setInt(6, re_step);
            pstmt.setInt(7, re_level);
            pstmt.setString(8, bean.getContent());
 
            pstmt.executeUpdate();
            con.close();
 
        } catch (Exception e) {
            e.printStackTrace();
        }
 
    }
 
    // 하나의 게시글을 읽어들이는 메소드 작성
    // 게시글을 읽었다는 뜻은 조회수가 1증가된다는 뜻
    // 게시글을 누르면 조회수도 올라가야함
    public BoardBean getOneBoard(int num) {
        getCon();
        // 초기값이니까 null을 준다.
        BoardBean bean = null;
        try {
            // 하나의 게시글을 읽었을때 조회수 증가
            String countsql = "update board set readcount = readcount+1 where num=?";
            pstmt = con.prepareStatement(countsql);
            pstmt.setInt(1, num);
            // 쿼리를 실행
            pstmt.executeUpdate();
 
            // 한 게시글에 대한 정보를 리턴해주는 쿼리를 작성
            String sql = "select * from board where num=?";
            pstmt = con.prepareStatement(sql);
            // ?에 값을 집어넣기
            pstmt.setInt(1, num);
            // 쿼리실행후 결과를 리턴
            rs = pstmt.executeQuery();
            if (rs.next()) {
                bean = new BoardBean();
                bean.setNum(rs.getInt(1));
                bean.setWriter(rs.getString(2));
                bean.setEmail(rs.getString(3));
                bean.setSubject(rs.getString(4));
                bean.setPassword(rs.getString(5));
                bean.setReg_date(rs.getDate(6).toString());
                bean.setRef(rs.getInt(7));
                bean.setRe_step(rs.getInt(8));
                bean.setRe_level(rs.getInt(9));
                bean.setReadcount(rs.getInt(10));
                bean.setContent(rs.getString(11));
 
            }
 
            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bean;
 
    }
 
    // 답변글을 저장하는 메소드
    public void reInsertBoard(BoardBean bean) {
        getCon();
        // 초기값 지정
        int ref = bean.getRef();
        int re_step = bean.getRe_step();
        int re_level = bean.getRe_level();
 
        try {
            // 쿼리 작성
            // 이 sql에서 1만 더하면 되기때문에 가장큰값을 검색
            // 답변형 게시판의 특징인 글을 쓰면 먼저쓴글이 가장 위로 올라가야 하기 때문에 다른글들은 다 밑으로 내려야한다.
            String relevelsql = "update board set re_level=re_level+1 where ref=? and re_level >?";
            pstmt = con.prepareStatement(relevelsql);
            pstmt.setInt(1, ref);
            pstmt.setInt(2, re_level);
 
            // 쿼리 실행후 결과를 리턴
            pstmt.executeUpdate();
 
            // 데이터를 삽입하는 쿼리
            String sql = "insert into board values(board_seq.NEXTVAL,?,?,?,?,sysdate,?,?,?,0,?)";
            pstmt = con.prepareStatement(sql);
            // ?에 값을 매핑한다.
            pstmt.setString(1, bean.getWriter());
            pstmt.setString(2, bean.getEmail());
            pstmt.setString(3, bean.getSubject());
            pstmt.setString(4, bean.getPassword());
            pstmt.setInt(5, ref);
            pstmt.setInt(6, re_step + 1); // 기존 부모글에 스텝보다 1을 증가시켜야 한다.
            pstmt.setInt(7, re_level + 1); // 기존 부모글에 스텝보다 1을 증가시켜야 한다.
            pstmt.setString(8, bean.getContent());
 
            pstmt.executeUpdate();
            con.close();
 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    // 조회수를 증가하지 않는 하나의 게시글을 리턴하는 메소드
    // 게시글 확인을 확인하는 메소드에서 조회수 증가 쿼리만 제외한다.
    public BoardBean getOneUpdateBoard(int num) {
        getCon();
        // 초기값이니까 null을 준다.
        BoardBean bean = null;
        try {
 
            // 한 게시글에 대한 정보를 리턴해주는 쿼리를 작성
            String sql = "select * from board where num=?";
            pstmt = con.prepareStatement(sql);
            // ?에 값을 집어넣기
            pstmt.setInt(1, num);
            // 쿼리실행후 결과를 리턴
            rs = pstmt.executeQuery();
            if (rs.next()) {
                bean = new BoardBean();
                bean.setNum(rs.getInt(1));
                bean.setWriter(rs.getString(2));
                bean.setEmail(rs.getString(3));
                bean.setSubject(rs.getString(4));
                bean.setPassword(rs.getString(5));
                bean.setReg_date(rs.getDate(6).toString());
                bean.setRef(rs.getInt(7));
                bean.setRe_step(rs.getInt(8));
                bean.setRe_level(rs.getInt(9));
                bean.setReadcount(rs.getInt(10));
                bean.setContent(rs.getString(11));
 
            }
 
            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bean;
    }
 
    // 하나의 게시글을 수정하는 메소드
    public void updateBoard(int num, String subject, String content) {
 
        // 데이터베이스 연결
        getCon();
        try {
            String sql = "update board set subject=?,content=? where num=?";
            pstmt = con.prepareStatement(sql);
            // ?에 값을 대입한다.
            pstmt.setString(1, subject);
            pstmt.setString(2, content);
            pstmt.setInt(3, num);
 
            // 4. 쿼리를 실행한다.
            pstmt.executeUpdate();
            // insert, delete, update 쿼리 구문은 executeUpdate를 사용한다.
            // 즉 DML(데이터조작어)를 사용할 때는 executeUpdate()를 사용한다.
            // 5. 자원 반납
            con.close();
 
        } catch (Exception e) {
            e.printStackTrace();
        }
 
    }
 
    // 하나의 게시글을 삭제하는 메소드
    public void deleteBoard(int num) {
 
        getCon();
 
        try {
            String sql = "delete from board where num=?";
            pstmt = con.prepareStatement(sql);
            // ?에 값을 넣어준다.
            pstmt.setInt(1, num);
            pstmt.executeUpdate();
            con.close();
 
        } catch (Exception e) {
            e.printStackTrace();
        }
 
    }
}
cs





:

19.05.26 jsp 게시판 게시글 수정 (model 2 동영상 19강~20강)

Back-End/JSP 2019. 5. 26. 13:51

게시글 수정 구현



BoardUpdateForm.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
.<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
    <center>
        <h2>게시글 수정</h2>
 
        <form action="BoardUpdateProcCon.do" method="post">
            <table width="600" border="1">
                <tr height="40">
 
                    <td width="160" align="center">작성자</td>
                    <td width="60" align="center">${bean.writer }</td>
 
                    <td width="160" align="center">작성일</td>
                    <td width="220" align="center">${bean.reg_date }</td>
                </tr>
 
                <tr height="40">
                    <td width="170" align="center">제목</td>
                    <td width="430" colspan="3">&nbsp; <input type="text"
                        name="subject" value="${bean.subject }" size="60"></td>
                </tr>
 
                <tr height="40">
                    <td width="200" align="center">패스워드</td>
                    <td width="400">&nbsp; <input type="password" name="password"
                        size="30"></td>
                </tr>
 
                <tr height="40">
                    <td width="170" align="center">글내용</td>
                    <td width="430" colspan="3"><textarea rows="10" cols="60"
                            name="content" align="left">${bean.content }</textarea></td>
                </tr>
 
                <tr height="40">
                    <td colspan="4" align="center"><input type="hidden" name="num"
                        value="${bean.num }"<!-- 패스워드를 히든으로 넘기면 한번더 db에 연결할 필요 없이 바로 패스워드가 맞는지 틀리는지 확인할 수 있다. -->
                        <input type="hidden" name="pass" value="${bean.password }">
                        <input type="submit" value="글수정"> &nbsp;&nbsp; <input
                        type="button" onclick="location.href='BoardListCon.do'"
                        value="전체글보기"></td>
                </tr>
            </table>
        </form>
    </center>
</body>
</html>
cs



BoardUpdateCon.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
.package control;
 
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;
 
import model.BoardBean;
import model.BoardDAO;
 
/**
 * Servlet implementation class BoardUpdateCon
 */
@WebServlet("/BoardUpdateCon.do")
public class BoardUpdateCon extends HttpServlet {
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        reqPro(request, response);
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        reqPro(request, response);
    }
 
    protected void reqPro(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
 
        // 해당 게시글의 번호를 먼저 읽어들인다. 그래야 게시글을 수정할 수 있기 때문
        int num = Integer.parseInt(request.getParameter("num"));
 
        // 데이터베이스에서 하나의 게시글에 대한 정보를 리턴하는 메소드 호출
 
        BoardDAO bdao = new BoardDAO();
        BoardBean bean = bdao.getOneUpdateBoard(num);
 
        // request에 데이터를 담기
        request.setAttribute("bean", bean);
 
        RequestDispatcher dis = request.getRequestDispatcher("BoardUpdateForm.jsp");
        dis.forward(request, response);
 
    }
 
}
 
cs



BoardUpdateProcCon.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 control;
 
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;
 
import model.BoardDAO;
 
/**
 * Servlet implementation class BoardUpdateProcCon
 */
//게시글 수정 처리 서블릿
//게시글 수정할 때 비밀번호를 입력해서 비밀번호가 맞으면 게시글을 수정할 수 있다.
@WebServlet("/BoardUpdateProcCon.do")
public class BoardUpdateProcCon extends HttpServlet {
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        reqPro(request, response);
    }
 
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        reqPro(request, response);
    }
 
    protected void reqPro(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 한글 처리
        request.setCharacterEncoding("euc-kr");
 
        // 폼에서 넘어온 데이터를 받아줌
        // 비밀번호를 받아서 db에 저장된 비밀번호와 맞는지 확인해서
        // 게시글 수정 가능
        int num = Integer.parseInt(request.getParameter("num"));
        String password = request.getParameter("password"); // 사용자로부터 입력받은 패스워드
        String pass = request.getParameter("pass"); // 실제 데이터베이스에 저장되어 있는 패스워드 값
        String subject = request.getParameter("subject");
        String content = request.getParameter("content");
 
        // password값과 pass값을 비교해서 맞으면 게시글 수정하게함.
        if (password.equals(pass)) {// 패스워드가 같다면 데이터를 수정
 
            BoardDAO bdao = new BoardDAO();
            // 패스워드는 비교만 하면 되기 때문에 따로 넘기지는 않고, 나머지 자료만 넘김
            // 왜냐하면 글 수정할때는 패스워드를 바꾸는게 아니라 제목, 내용만 바뀌는 것이기 때문
            bdao.updateBoard(num, subject, content);
            // 수정이 완료되었을시에 실행하고 게시물 리스트 페이지로 이동시킨다.
            request.setAttribute("msg""수정이 완료되었습니다.");
            RequestDispatcher dis = request.getRequestDispatcher("BoardListCon.do");
            dis.forward(request, response);
        } else {
            // 비밀번호가 틀렸다면 이전 페이지로 이동하고 실행
            request.setAttribute("msg""비밀번호가 맞지 않습니다.");
            RequestDispatcher dis = request.getRequestDispatcher("BoardListCon.do");
            dis.forward(request, response);
 
        }
    }
 
}
 
cs



BoardDAO.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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
.package model;
 
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 BoardDAO {
 
    Connection con;
    PreparedStatement pstmt;
    ResultSet rs;
 
    // 데이터 베이스에 연결 메소드
    public void getCon() {
        try {
            Context initctx = new InitialContext();
            Context envctx = (Context) initctx.lookup("java:comp/env");
            // 타입이 데이터 소스이므로 데이터소스로 (타입변환해서) 받는다.
            DataSource ds = (DataSource) envctx.lookup("jdbc/pool");
            // 얻은 데이터소스를 사용해 연결한다.
            con = ds.getConnection(); // 커넥션 연결 해주는 메소드
 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    // 전체 게시글의 갯수를 리턴하는 메소드
    public int getAllCount() {
        getCon();
        // 개시글의 갯수를 세야하기 때문에 카운트 변수를 추가하고 초기값을 선언한다.
        int count = 0;
 
        try {
            // sql 쿼리 준비함
            String sql = "select count(*) from board";
            pstmt = con.prepareStatement(sql);
            // ?표가 없으므로 바로 결과실행후 리턴시켜주면 된다.
            rs = pstmt.executeQuery();
            // 전체게시글은 한칸에서 밖에 출력이 되지 않으므로 1칸만 있으면 된다. 반복문 말고 if문으로 사용한다.
            if (rs.next()) { // 데이터가 있다면 카운트에 넣는다.
                // 전체 게시글 수
                count = rs.getInt(1);
            }
            con.close();
 
        } catch (Exception e) {
            e.printStackTrace();
        }
        return count;
    }
 
    // 화면에 보여질 데이터를 10개씩 추출해서 리턴하는 메소드
    public Vector<BoardBean> getAllBoard(int startRow, int endRow) {
        // 리턴할객체 선언
        getCon();
        Vector<BoardBean> v = new Vector<>();
        try {
            // 쿼리 작성
            String sql = "select * from (select A.*, Rownum Rnum from (select * from board order by ref desc, re_step asc)A)"
                    + "where Rnum >= ? and Rnum <= ?";
            // 쿼리 실행할 객체를 선언
            pstmt = con.prepareStatement(sql);
            pstmt.setInt(1, startRow);
            pstmt.setInt(2, endRow);
            // 쿼리실행후 결과 저장
            rs = pstmt.executeQuery();
            // 데이터 개수가 몇개인지 모르기에 반복문을 이용하여 데이터를 추출
            while (rs.next()) {
                // 데이터를 패키징 ( BoardBean 클래스를 이용) 해줌
                BoardBean bean = new BoardBean();
                bean.setNum(rs.getInt(1));
                bean.setWriter(rs.getString(2));
                bean.setEmail(rs.getString(3));
                bean.setSubject(rs.getString(4));
                bean.setPassword(rs.getString(5));
                bean.setReg_date(rs.getDate(6).toString());
                bean.setRef(rs.getInt(7));
                bean.setRe_step(rs.getInt(8));
                bean.setRe_level(rs.getInt(9));
                bean.setReadcount(rs.getInt(10));
                bean.setContent(rs.getString(11));
                // 패키징한 데이터를 벡터에 저장
                v.add(bean);
            }
            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return v;
    }
 
    // 하나의 게시글을 저장하는 메소드 호출
    public void insertBoard(BoardBean bean) {
 
        getCon();
        // 초기값 지정
        int ref = 0;
        int re_step = 1;// 새글이기에
        int re_level = 1;// 새글이기에
 
        try {
            // 쿼리 작성
            // 이 sql에서 1만 더하면 되기때문에 가장큰값을 검색
            String refsql = "select max(ref) from board";
            pstmt = con.prepareStatement(refsql);
            // 쿼리 실행후 결과를 리턴
            rs = pstmt.executeQuery();
            if (rs.next()) {
                ref = rs.getInt(1+ 1// ref가장 큰 값에 1을 더해줌
                // 최신글은 글번호가 가장 크기 때문에 원래 있던 글에서 1을 더해줌
 
            }
            // 데이터를 삽입하는 쿼리
            String sql = "insert into board values(board_seq.NEXTVAL,?,?,?,?,sysdate,?,?,?,0,?)";
            pstmt = con.prepareStatement(sql);
            // ?에 값을 매핑한다.
            pstmt.setString(1, bean.getWriter());
            pstmt.setString(2, bean.getEmail());
            pstmt.setString(3, bean.getSubject());
            pstmt.setString(4, bean.getPassword());
            pstmt.setInt(5, ref);
            pstmt.setInt(6, re_step);
            pstmt.setInt(7, re_level);
            pstmt.setString(8, bean.getContent());
 
            pstmt.executeUpdate();
            con.close();
 
        } catch (Exception e) {
            e.printStackTrace();
        }
 
    }
 
    // 하나의 게시글을 읽어들이는 메소드 작성
    // 게시글을 읽었다는 뜻은 조회수가 1증가된다는 뜻
    // 게시글을 누르면 조회수도 올라가야함
    public BoardBean getOneBoard(int num) {
        getCon();
        // 초기값이니까 null을 준다.
        BoardBean bean = null;
        try {
            // 하나의 게시글을 읽었을때 조회수 증가
            String countsql = "update board set readcount = readcount+1 where num=?";
            pstmt = con.prepareStatement(countsql);
            pstmt.setInt(1, num);
            // 쿼리를 실행
            pstmt.executeUpdate();
 
            // 한 게시글에 대한 정보를 리턴해주는 쿼리를 작성
            String sql = "select * from board where num=?";
            pstmt = con.prepareStatement(sql);
            // ?에 값을 집어넣기
            pstmt.setInt(1, num);
            // 쿼리실행후 결과를 리턴
            rs = pstmt.executeQuery();
            if (rs.next()) {
                bean = new BoardBean();
                bean.setNum(rs.getInt(1));
                bean.setWriter(rs.getString(2));
                bean.setEmail(rs.getString(3));
                bean.setSubject(rs.getString(4));
                bean.setPassword(rs.getString(5));
                bean.setReg_date(rs.getDate(6).toString());
                bean.setRef(rs.getInt(7));
                bean.setRe_step(rs.getInt(8));
                bean.setRe_level(rs.getInt(9));
                bean.setReadcount(rs.getInt(10));
                bean.setContent(rs.getString(11));
 
            }
 
            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bean;
 
    }
 
    // 답변글을 저장하는 메소드
    public void reInsertBoard(BoardBean bean) {
        getCon();
        // 초기값 지정
        int ref = bean.getRef();
        int re_step = bean.getRe_step();
        int re_level = bean.getRe_level();
 
        try {
            // 쿼리 작성
            // 이 sql에서 1만 더하면 되기때문에 가장큰값을 검색
            // 답변형 게시판의 특징인 글을 쓰면 먼저쓴글이 가장 위로 올라가야 하기 때문에 다른글들은 다 밑으로 내려야한다.
            String relevelsql = "update board set re_level=re_level+1 where ref=? and re_level >?";
            pstmt = con.prepareStatement(relevelsql);
            pstmt.setInt(1, ref);
            pstmt.setInt(2, re_level);
 
            // 쿼리 실행후 결과를 리턴
            pstmt.executeUpdate();
 
            // 데이터를 삽입하는 쿼리
            String sql = "insert into board values(board_seq.NEXTVAL,?,?,?,?,sysdate,?,?,?,0,?)";
            pstmt = con.prepareStatement(sql);
            // ?에 값을 매핑한다.
            pstmt.setString(1, bean.getWriter());
            pstmt.setString(2, bean.getEmail());
            pstmt.setString(3, bean.getSubject());
            pstmt.setString(4, bean.getPassword());
            pstmt.setInt(5, ref);
            pstmt.setInt(6, re_step + 1); // 기존 부모글에 스텝보다 1을 증가시켜야 한다.
            pstmt.setInt(7, re_level + 1); // 기존 부모글에 스텝보다 1을 증가시켜야 한다.
            pstmt.setString(8, bean.getContent());
 
            pstmt.executeUpdate();
            con.close();
 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    // 조회수를 증가하지 않는 하나의 게시글을 리턴하는 메소드
    // 게시글 확인을 확인하는 메소드에서 조회수 증가 쿼리만 제외한다.
    public BoardBean getOneUpdateBoard(int num) {
        getCon();
        // 초기값이니까 null을 준다.
        BoardBean bean = null;
        try {
 
            // 한 게시글에 대한 정보를 리턴해주는 쿼리를 작성
            String sql = "select * from board where num=?";
            pstmt = con.prepareStatement(sql);
            // ?에 값을 집어넣기
            pstmt.setInt(1, num);
            // 쿼리실행후 결과를 리턴
            rs = pstmt.executeQuery();
            if (rs.next()) {
                bean = new BoardBean();
                bean.setNum(rs.getInt(1));
                bean.setWriter(rs.getString(2));
                bean.setEmail(rs.getString(3));
                bean.setSubject(rs.getString(4));
                bean.setPassword(rs.getString(5));
                bean.setReg_date(rs.getDate(6).toString());
                bean.setRef(rs.getInt(7));
                bean.setRe_step(rs.getInt(8));
                bean.setRe_level(rs.getInt(9));
                bean.setReadcount(rs.getInt(10));
                bean.setContent(rs.getString(11));
 
            }
 
            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bean;
    }
 
    // 하나의 게시글을 수정하는 메소드
    public void updateBoard(int num, String subject, String content) {
 
        // 데이터베이스 연결
        getCon();
        try {
            String sql = "update board set subject=?,content=? where num=?";
            pstmt = con.prepareStatement(sql);
            // ?에 값을 대입한다.
            pstmt.setString(1, subject);
            pstmt.setString(2, content);
            pstmt.setInt(3, num);
 
            // 4. 쿼리를 실행한다.
            pstmt.executeUpdate();
            // insert, delete, update 쿼리 구문은 executeUpdate를 사용한다.
            // 즉 DML(데이터조작어)를 사용할 때는 executeUpdate()를 사용한다.
            // 5. 자원 반납
            con.close();
 
        } catch (Exception e) {
            e.printStackTrace();
        }
 
    }
}
cs



:

19.05.26 jsp 게시판 답글 작성 (model 2 동영상 18강)

Back-End/JSP 2019. 5. 26. 13:33

답글 작성 구현





BoardReWriteForm.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
<%@ 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>
        <h2>답변글 입력하기</h2>
 
        <form action="BoardReWriteProcCon.do" method="post">
            <!-- 답변글 처리 페이지로 자료를 전달 -->
            <table width="600" border="1" bordercolor="gray" bgcolor="skyblue">
 
                <tr height="40">
                    <td width="150" align="center">작성자</td>
                    <td width="450"><input type="text" name="writer" size="60"></td>
                </tr>
 
                <tr height="40">
                    <td width="150" align="center">제목</td>
                    <td width="450"><input type="text" name="subject" value="[답변]"
                        size="60"></td>
                </tr>
 
                <tr height="40">
                    <td width="150" align="center">이메일</td>
                    <td width="450"><input type="email" name="email" size="60"></td>
                </tr>
 
                <tr height="40">
                    <td width="150" align="center">비밀번호</td>
                    <td width="450"><input type="password" name="password"
                        size="60"></td>
                </tr>
 
                <tr height="40">
                    <td width="150" align="center">글내용</td>
                    <td width="450"><textarea rows="10" cols="60" name="content"></textarea></td>
                </tr>
                <!-- form에서 사용자로부터 입력 받지 않고 데이터를 넘김 -->
                <tr height="40">
                    <!-- 각 데이터에 맞는 버튼을 만들어준다. -->
                    <td align="center" colspan="2"><input type="hidden" name="ref"
                        value="${ref }"> <input type="hidden" name="re_step"
                        value="${re_step }"> <input type="hidden" name="re_level"
                        value="${re_level }"> <input type="submit" value="답글쓰기완료">
                        &nbsp;&nbsp; <input type="reset" value="취소"> &nbsp;&nbsp;
                        <input type="button" onclick="location.href='BoardListCon.do'"
                        value="전체글보기"></td>
                    <!-- 리스트 화면으로 돌아가는 버튼 -->
                </tr>
 
            </table>
        </form>
    </center>
</body>
</html>
cs



BoardReWriteCon.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
.package control;
 
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;
 
import model.BoardBean;
import model.BoardDAO;
 
/**
 * Servlet implementation class BoardWriteProcCon
 */
// 글쓰기 처리 서블릿 선언
@WebServlet("/BoardReWriteCon.do")
public class BoardReWriteCon extends HttpServlet {
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        reqPro(request, response);
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        reqPro(request, response);
    }
 
    protected void reqPro(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
 
        // 한글타입이 아니기 때문에 한글처리는 안해도됨
        // 답글쓰기 같은 경우는 시퀀스가 있기때문에 자동으로 부여되서
        // 궂이 num값을 받아서 할 필요가 없다
        // Integer.pareInt는 문자를 int형식으로 변환할때 사용
        int ref = Integer.parseInt(request.getParameter("ref"));
        int re_step = Integer.parseInt(request.getParameter("re_step"));
        int re_level = Integer.parseInt(request.getParameter("re_level"));
 
        // 글관련 정보들을 다른페이지로 넘겨주기 위해서 담아놓는다.
        request.setAttribute("ref", ref);
        request.setAttribute("re_step", re_step);
        request.setAttribute("re_level", re_level);
 
        // BoardReWriteForm.jsp파일에 request, response에 담아놓은 자료들을 넘겨준다.
        RequestDispatcher dis = request.getRequestDispatcher("BoardReWriteForm.jsp");
        dis.forward(request, response);
    }
}
cs



BoardReWriteProcCon.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
.package control;
 
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;
 
import model.BoardBean;
import model.BoardDAO;
 
/**
 * Servlet implementation class BoardReWriteProcCon
 */
@WebServlet("/BoardReWriteProcCon.do")
public class BoardReWriteProcCon extends HttpServlet {
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        reqPro(request, response);
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        reqPro(request, response);
    }
 
    protected void reqPro(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 빈클래스안에 받아온 데이터를 저장
        BoardBean bean = new BoardBean();
 
        request.setCharacterEncoding("euc-kr");
 
        bean.setWriter(request.getParameter("writer"));
        bean.setSubject(request.getParameter("subject"));
        bean.setEmail(request.getParameter("email"));
        bean.setPassword(request.getParameter("password"));
        bean.setContent(request.getParameter("content"));
 
        bean.setRef(Integer.parseInt(request.getParameter("ref")));
        bean.setRe_step(Integer.parseInt(request.getParameter("re_step")));
        bean.setRe_level(Integer.parseInt(request.getParameter("re_level")));
 
        BoardDAO bdao = new BoardDAO();
        // DAO클래스에 Insert메서드에 빈을 매개변수로 넘겨준다.
        bdao.reInsertBoard(bean);
 
        RequestDispatcher dis = request.getRequestDispatcher("BoardListCon.do");
        dis.forward(request, response);
 
    }
}
 
cs



BoardDAO.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
.package model;
 
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 BoardDAO {
 
    Connection con;
    PreparedStatement pstmt;
    ResultSet rs;
 
    // 데이터 베이스에 연결 메소드
    public void getCon() {
        try {
            Context initctx = new InitialContext();
            Context envctx = (Context) initctx.lookup("java:comp/env");
            // 타입이 데이터 소스이므로 데이터소스로 (타입변환해서) 받는다.
            DataSource ds = (DataSource) envctx.lookup("jdbc/pool");
            // 얻은 데이터소스를 사용해 연결한다.
            con = ds.getConnection(); // 커넥션 연결 해주는 메소드
 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    // 전체 게시글의 갯수를 리턴하는 메소드
    public int getAllCount() {
        getCon();
        // 개시글의 갯수를 세야하기 때문에 카운트 변수를 추가하고 초기값을 선언한다.
        int count = 0;
 
        try {
            // sql 쿼리 준비함
            String sql = "select count(*) from board";
            pstmt = con.prepareStatement(sql);
            // ?표가 없으므로 바로 결과실행후 리턴시켜주면 된다.
            rs = pstmt.executeQuery();
            // 전체게시글은 한칸에서 밖에 출력이 되지 않으므로 1칸만 있으면 된다. 반복문 말고 if문으로 사용한다.
            if (rs.next()) { // 데이터가 있다면 카운트에 넣는다.
                // 전체 게시글 수
                count = rs.getInt(1);
            }
            con.close();
 
        } catch (Exception e) {
            e.printStackTrace();
        }
        return count;
    }
 
    // 화면에 보여질 데이터를 10개씩 추출해서 리턴하는 메소드
    public Vector<BoardBean> getAllBoard(int startRow, int endRow) {
        // 리턴할객체 선언
        getCon();
        Vector<BoardBean> v = new Vector<>();
        try {
            // 쿼리 작성
            String sql = "select * from (select A.*, Rownum Rnum from (select * from board order by ref desc, re_step asc)A)"
                    + "where Rnum >= ? and Rnum <= ?";
            // 쿼리 실행할 객체를 선언
            pstmt = con.prepareStatement(sql);
            pstmt.setInt(1, startRow);
            pstmt.setInt(2, endRow);
            // 쿼리실행후 결과 저장
            rs = pstmt.executeQuery();
            // 데이터 개수가 몇개인지 모르기에 반복문을 이용하여 데이터를 추출
            while (rs.next()) {
                // 데이터를 패키징 ( BoardBean 클래스를 이용) 해줌
                BoardBean bean = new BoardBean();
                bean.setNum(rs.getInt(1));
                bean.setWriter(rs.getString(2));
                bean.setEmail(rs.getString(3));
                bean.setSubject(rs.getString(4));
                bean.setPassword(rs.getString(5));
                bean.setReg_date(rs.getDate(6).toString());
                bean.setRef(rs.getInt(7));
                bean.setRe_step(rs.getInt(8));
                bean.setRe_level(rs.getInt(9));
                bean.setReadcount(rs.getInt(10));
                bean.setContent(rs.getString(11));
                // 패키징한 데이터를 벡터에 저장
                v.add(bean);
            }
            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return v;
    }
 
    // 하나의 게시글을 저장하는 메소드 호출
    public void insertBoard(BoardBean bean) {
 
        getCon();
        // 초기값 지정
        int ref = 0;
        int re_step = 1;// 새글이기에
        int re_level = 1;// 새글이기에
 
        try {
            // 쿼리 작성
            // 이 sql에서 1만 더하면 되기때문에 가장큰값을 검색
            String refsql = "select max(ref) from board";
            pstmt = con.prepareStatement(refsql);
            // 쿼리 실행후 결과를 리턴
            rs = pstmt.executeQuery();
            if (rs.next()) {
                ref = rs.getInt(1+ 1// ref가장 큰 값에 1을 더해줌
                // 최신글은 글번호가 가장 크기 때문에 원래 있던 글에서 1을 더해줌
 
            }
            // 데이터를 삽입하는 쿼리
            String sql = "insert into board values(board_seq.NEXTVAL,?,?,?,?,sysdate,?,?,?,0,?)";
            pstmt = con.prepareStatement(sql);
            // ?에 값을 매핑한다.
            pstmt.setString(1, bean.getWriter());
            pstmt.setString(2, bean.getEmail());
            pstmt.setString(3, bean.getSubject());
            pstmt.setString(4, bean.getPassword());
            pstmt.setInt(5, ref);
            pstmt.setInt(6, re_step);
            pstmt.setInt(7, re_level);
            pstmt.setString(8, bean.getContent());
 
            pstmt.executeUpdate();
            con.close();
 
        } catch (Exception e) {
            e.printStackTrace();
        }
 
    }
 
    // 하나의 게시글을 읽어들이는 메소드 작성
    // 게시글을 읽었다는 뜻은 조회수가 1증가된다는 뜻
    // 게시글을 누르면 조회수도 올라가야함
    public BoardBean getOneBoard(int num) {
        getCon();
        // 초기값이니까 null을 준다.
        BoardBean bean = null;
        try {
            // 하나의 게시글을 읽었을때 조회수 증가
            String countsql = "update board set readcount = readcount+1 where num=?";
            pstmt = con.prepareStatement(countsql);
            pstmt.setInt(1, num);
            // 쿼리를 실행
            pstmt.executeUpdate();
 
            // 한 게시글에 대한 정보를 리턴해주는 쿼리를 작성
            String sql = "select * from board where num=?";
            pstmt = con.prepareStatement(sql);
            // ?에 값을 집어넣기
            pstmt.setInt(1, num);
            // 쿼리실행후 결과를 리턴
            rs = pstmt.executeQuery();
            if (rs.next()) {
                bean = new BoardBean();
                bean.setNum(rs.getInt(1));
                bean.setWriter(rs.getString(2));
                bean.setEmail(rs.getString(3));
                bean.setSubject(rs.getString(4));
                bean.setPassword(rs.getString(5));
                bean.setReg_date(rs.getDate(6).toString());
                bean.setRef(rs.getInt(7));
                bean.setRe_step(rs.getInt(8));
                bean.setRe_level(rs.getInt(9));
                bean.setReadcount(rs.getInt(10));
                bean.setContent(rs.getString(11));
 
            }
 
            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bean;
 
    }
 
    // 답변글을 저장하는 메소드
    public void reInsertBoard(BoardBean bean) {
        getCon();
        // 초기값 지정
        int ref = bean.getRef();
        int re_step = bean.getRe_step();
        int re_level = bean.getRe_level();
 
        try {
            // 쿼리 작성
            // 이 sql에서 1만 더하면 되기때문에 가장큰값을 검색
            // 답변형 게시판의 특징인 글을 쓰면 먼저쓴글이 가장 위로 올라가야 하기 때문에 다른글들은 다 밑으로 내려야한다.
            String relevelsql = "update board set re_level=re_level+1 where ref=? and re_level >?";
            pstmt = con.prepareStatement(relevelsql);
            pstmt.setInt(1, ref);
            pstmt.setInt(2, re_level);
 
            // 쿼리 실행후 결과를 리턴
            pstmt.executeUpdate();
 
            // 데이터를 삽입하는 쿼리
            String sql = "insert into board values(board_seq.NEXTVAL,?,?,?,?,sysdate,?,?,?,0,?)";
            pstmt = con.prepareStatement(sql);
            // ?에 값을 매핑한다.
            pstmt.setString(1, bean.getWriter());
            pstmt.setString(2, bean.getEmail());
            pstmt.setString(3, bean.getSubject());
            pstmt.setString(4, bean.getPassword());
            pstmt.setInt(5, ref);
            pstmt.setInt(6, re_step + 1); // 기존 부모글에 스텝보다 1을 증가시켜야 한다.
            pstmt.setInt(7, re_level + 1); // 기존 부모글에 스텝보다 1을 증가시켜야 한다.
            pstmt.setString(8, bean.getContent());
 
            pstmt.executeUpdate();
            con.close();
 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
cs




:

19.05.25 jsp 게시판 내용 확인 (model 2 동영상 17강)

Back-End/JSP 2019. 5. 25. 22:14

게시글 내용 확인 구현



BoardInfoControl.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
package control;
 
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;
 
import model.BoardBean;
import model.BoardDAO;
 
//게시글 정보를 처리하는 서블릿
@WebServlet("/BoardInfoControl.do")
public class BoardInfoControl extends HttpServlet {
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        rePro(request, response);
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        rePro(request, response);
    }
 
    protected void rePro(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
 
        // num을 포장클래스를 이용해 타입변환을 시켜서 num에 넣는다. (게시글 번호)
        int num = Integer.parseInt(request.getParameter("num"));
 
        // 데이터베이스에 접근
        BoardDAO bdao = new BoardDAO();
        // 하나의 게시글에 대한 정보를 리턴
        BoardBean bean = bdao.getOneBoard(num);
 
        request.setAttribute("bean", bean);
 
        // view (jsp를 의미한다) 쪽으로 데이터를 넘겨준다.
        // BoardInfo.jsp로 request, response를 전달
        RequestDispatcher dis = request.getRequestDispatcher("BoardInfo.jsp");
        dis.forward(request, response);
    }
 
}
 
cs



BoardDAO (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
package model;
 
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 BoardDAO {
 
    Connection con;
    PreparedStatement pstmt;
    ResultSet rs;
 
    // 데이터 베이스에 연결 메소드
    public void getCon() {
        try {
            Context initctx = new InitialContext();
            Context envctx = (Context) initctx.lookup("java:comp/env");
            // 타입이 데이터 소스이므로 데이터소스로 (타입변환해서) 받는다.
            DataSource ds = (DataSource) envctx.lookup("jdbc/pool");
            // 얻은 데이터소스를 사용해 연결한다.
            con = ds.getConnection(); // 커넥션 연결 해주는 메소드
 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    // 전체 게시글의 갯수를 리턴하는 메소드
    public int getAllCount() {
        getCon();
        // 개시글의 갯수를 세야하기 때문에 카운트 변수를 추가하고 초기값을 선언한다.
        int count = 0;
 
        try {
            // sql 쿼리 준비함
            String sql = "select count(*) from board";
            pstmt = con.prepareStatement(sql);
            // ?표가 없으므로 바로 결과실행후 리턴시켜주면 된다.
            rs = pstmt.executeQuery();
            // 전체게시글은 한칸에서 밖에 출력이 되지 않으므로 1칸만 있으면 된다. 반복문 말고 if문으로 사용한다.
            if (rs.next()) { // 데이터가 있다면 카운트에 넣는다.
                // 전체 게시글 수
                count = rs.getInt(1);
            }
            con.close();
 
        } catch (Exception e) {
            e.printStackTrace();
        }
        return count;
    }
 
    // 화면에 보여질 데이터를 10개씩 추출해서 리턴하는 메소드
    public Vector<BoardBean> getAllBoard(int startRow, int endRow) {
        // 리턴할객체 선언
        getCon();
        Vector<BoardBean> v = new Vector<>();
        try {
            // 쿼리 작성
            String sql = "select * from (select A.*, Rownum Rnum from (select * from board order by ref desc, re_step asc)A)"
                    + "where Rnum >= ? and Rnum <= ?";
            // 쿼리 실행할 객체를 선언
            pstmt = con.prepareStatement(sql);
            pstmt.setInt(1, startRow);
            pstmt.setInt(2, endRow);
            // 쿼리실행후 결과 저장
            rs = pstmt.executeQuery();
            // 데이터 개수가 몇개인지 모르기에 반복문을 이용하여 데이터를 추출
            while (rs.next()) {
                // 데이터를 패키징 ( BoardBean 클래스를 이용) 해줌
                BoardBean bean = new BoardBean();
                bean.setNum(rs.getInt(1));
                bean.setWriter(rs.getString(2));
                bean.setEmail(rs.getString(3));
                bean.setSubject(rs.getString(4));
                bean.setPassword(rs.getString(5));
                bean.setReg_date(rs.getDate(6).toString());
                bean.setRef(rs.getInt(7));
                bean.setRe_step(rs.getInt(8));
                bean.setRe_level(rs.getInt(9));
                bean.setReadcount(rs.getInt(10));
                bean.setContent(rs.getString(11));
                // 패키징한 데이터를 벡터에 저장
                v.add(bean);
            }
            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return v;
    }
 
    // 하나의 게시글을 저장하는 메소드 호출
    public void insertBoard(BoardBean bean) {
 
        getCon();
        // 초기값 지정
        int ref = 0;
        int re_step = 1;// 새글이기에
        int re_level = 1;// 새글이기에
 
        try {
            // 쿼리 작성
            // 이 sql에서 1만 더하면 되기때문에 가장큰값을 검색
            String refsql = "select max(ref) from board";
            pstmt = con.prepareStatement(refsql);
            // 쿼리 실행후 결과를 리턴
            rs = pstmt.executeQuery();
            if (rs.next()) {
                ref = rs.getInt(1+ 1// ref가장 큰 값에 1을 더해줌
                // 최신글은 글번호가 가장 크기 때문에 원래 있던 글에서 1을 더해줌
 
            }
            // 데이터를 삽입하는 쿼리
            String sql = "insert into board values(board_seq.NEXTVAL,?,?,?,?,sysdate,?,?,?,0,?)";
            pstmt = con.prepareStatement(sql);
            // ?에 값을 매핑한다.
            pstmt.setString(1, bean.getWriter());
            pstmt.setString(2, bean.getEmail());
            pstmt.setString(3, bean.getSubject());
            pstmt.setString(4, bean.getPassword());
            pstmt.setInt(5, ref);
            pstmt.setInt(6, re_step);
            pstmt.setInt(7, re_level);
            pstmt.setString(8, bean.getContent());
 
            pstmt.executeUpdate();
            con.close();
 
        } catch (Exception e) {
            e.printStackTrace();
        }
 
    }
 
    // 하나의 게시글을 읽어들이는 메소드 작성
    // 게시글을 읽었다는 뜻은 조회수가 1증가된다는 뜻
    // 게시글을 누르면 조회수도 올라가야함
    public BoardBean getOneBoard(int num) {
        getCon();
        // 초기값이니까 null을 준다.
        BoardBean bean = null;
        try {
            // 하나의 게시글을 읽었을때 조회수 증가
            String countsql = "update board set readcount = readcount+1 where num=?";
            pstmt = con.prepareStatement(countsql);
            pstmt.setInt(1, num);
            // 쿼리를 실행
            pstmt.executeUpdate();
 
            // 한 게시글에 대한 정보를 리턴해주는 쿼리를 작성
            String sql = "select * from board where num=?";
            pstmt = con.prepareStatement(sql);
            // ?에 값을 집어넣기
            pstmt.setInt(1, num);
            // 쿼리실행후 결과를 리턴
            rs = pstmt.executeQuery();
            if (rs.next()) {
                bean = new BoardBean();
                bean.setNum(rs.getInt(1));
                bean.setWriter(rs.getString(2));
                bean.setEmail(rs.getString(3));
                bean.setSubject(rs.getString(4));
                bean.setPassword(rs.getString(5));
                bean.setReg_date(rs.getDate(6).toString());
                bean.setRef(rs.getInt(7));
                bean.setRe_step(rs.getInt(8));
                bean.setRe_level(rs.getInt(9));
                bean.setReadcount(rs.getInt(10));
                bean.setContent(rs.getString(11));
 
            }
 
            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bean;
 
    }
}
cs



BoardInfo.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>
    <center>
        <h2>게시글 보기</h2>
 
        <table width="600" border="1">
            <tr height="40">
                <td align="center" width="120">글 번호</td>
                <td align="center" width="180">${bean.num }</td>
                <td align="center" width="120">조회수</td>
                <td align="center" width="180">${bean.readcount }</td>
            </tr>
 
            <tr height="40">
                <td align="center" width="120">작성자</td>
                <td align="center" width="180">${bean.writer }</td>
                <td align="center" width="120">작성일</td>
                <td align="center" width="180">${bean.reg_date}</td>
            </tr>
 
            <tr height="40">
                <td align="center" width="120" colspan="2">이메일</td>
                <td align="center" width="180" colspan="2">${bean.email }</td>
            </tr>
 
            <tr height="40">
                <td align="center" width="120">제목</td>
                <td align="center" colspan="3">${bean.subject }</td>
            </tr>
 
            <tr height="80">
                <td align="center" width="120">글 내용</td>
                <td align="center" colspan="3">${bean.content }</td>
            </tr>
 
 
            <!-- 답글쓰기는 게시글 번호 그룹등을 다 넘겨주어야 한다. 게시글의 번호가 바뀌기 때문 -->
            <tr height="40">
                <td align="center" colspan="4"><input type="button"
                    value="답글쓰기"
                    onclick="location.href='BoardReWriteCon.do?num=${bean.num }&ref=${bean.ref }&re_step=${bean.re_step }&re_level=${bean.re_level }'">
                    <!-- 부모글의 ref, revel, num값을 다 알고 있어야된다.(리플달기이기 때문) --> <!-- 위에처럼 num값만 넘겨서 할수도 있다.
        int num = Integer.parseInt(request.getParameter("num").trim());
        BoardDAO bdao = new BoardDAO();
        BoardBean bean = bdao.getOneBoard(num); --> <input type="button"
                    value="수정하기"
                    onclick="location.href = 'BoardUpdateCon.do?num=${bean.num}'">
                    <input type="button" value="삭제하기"
                    onclick="location.href = 'BoardDeleteCon.do?num=${bean.num }'">
                    <input type="button" value="목록보기"
                    onclick="location.href = 'BoardListCon.do'">
        </table>
    </center>
 
 
 
 
 
</body>
</html>
cs



:

19.05.25 jsp 게시판 쓰기 (model 2 동영상 16강)

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

게시판 글쓰기 구현




BoardWriteForm.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
<%@ 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>
        <h2>게시글 쓰기</h2>
        <!-- 컨트롤러가 읽어들이게끔 페이지 이동시킴 -->
        <form action="BoardWriteProcCon.do" method="post">
            <table width="600" border="1" bordercolor="gray" bgcolor="skyblue">
                <!-- bordercolor는 선색깔 지정 -->
                <tr height="40">
                    <td align="center" width="150">작성자</td>
                    <!-- ref는 데이터베이스에서 처리하기 때문에 따로 받지 않는다. -->
                    <td width="450"><input type="text" name="writer" size="60"></td>
                </tr>
 
                <tr height="40">
                    <td align="center" width="150">제목</td>
                    <td width="450"><input type="text" name="subject" size="60"></td>
                </tr>
 
                <tr height="40">
                    <td align="center" width="150">이메일</td>
                    <td width="450"><input type="text" name="email" size="60"></td>
                </tr>
 
                <tr height="40">
                    <td align="center" width="150">비밀번호</td>
                    <td width="450"><input type="password" name="password"
                        size="61"></td>
                </tr>
 
                <tr height="40">
                    <td align="center" width="150">글내용</td>
                    <td width="450"><textarea rows="10" cols="50" name="content"></textarea></td>
                </tr>
 
                <tr height="40">
                    <td align="center" colspan="2"><input type="submit"
                        value="글쓰기"> &nbsp;&nbsp; <input type="reset" value="다시작성">
                        &nbsp;&nbsp;
                        <button onclick="location.href='BoardListCon.do'">전체 게시글 보기</button>
                        <!-- 클릭하면 BoardList.jsp페이지로 넘어가는 버튼--></td>
                </tr>
            </table>
        </form>
    </center>
</body>
</html>
 
cs



BoardWriteProcCon.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
package control;
 
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;
 
import model.BoardBean;
import model.BoardDAO;
 
/**
 * Servlet implementation class BoardWriteProcCon
 */
// 글쓰기 처리 서블릿 선언
@WebServlet("/BoardWriteProcCon.do")
public class BoardWriteProcCon extends HttpServlet {
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        reqPro(request, response);
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        reqPro(request, response);
    }
 
    protected void reqPro(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("euc-kr");
        // 빈 클래스로 데이터를 읽어들인다.
        BoardBean bean = new BoardBean();
 
        // 5개의 값을 빈 클래스에 저장시킨다.
        bean.setWriter(request.getParameter("writer"));
        bean.setSubject(request.getParameter("subject"));
        bean.setEmail(request.getParameter("email"));
        bean.setPassword(request.getParameter("password"));
        bean.setContent(request.getParameter("content"));
 
        BoardDAO bdao = new BoardDAO();
        // insert메소드에 매개값으로 빈클래스가 가지고있는 값들을 넣어준다.
        bdao.insertBoard(bean);
 
        // BoardListCon.do로 request, response를 전달한다.
        RequestDispatcher dis = request.getRequestDispatcher("BoardListCon.do");
        dis.forward(request, response);
    }
}
 
cs



BoardListCon.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
package control;
 
import java.io.IOException;
import java.util.Vector;
 
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;
 
import model.BoardBean;
import model.BoardDAO;
 
/**
 * Servlet implementation class BoardListCon
 */
//웹 서블릿 url 설정
@WebServlet("/BoardListCon.do")
public class BoardListCon extends HttpServlet {
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        reqPro(request, response);
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        reqPro(request, response);
    }
 
    protected void reqPro(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // jsp쪽에서 출력되게끔 자료를 넘겨주어야 한다.
 
        // 화면에 보여질 게시글의 개수를 지정
        int pageSize = 10;
 
        // 현재 보여지고 있는 페이지의 넘버값을 읽어들인다.
        String pageNum = request.getParameter("pageNum");
 
        // null 처리
        if (pageNum == null) {
            pageNum = "1";
        }
        // 전체 게시글의 갯수
        int count = 0;
        // jsp 페이지 내에서 보여질 넘버링 숫자값을 저장하는 변수 선언
        int number = 0;
 
        // 현재 보여지고 있는 페이지 문자를 숫자로 변환
        int currentPage = Integer.parseInt(pageNum);
        // 전체 게시글의 갯수를 가져와야 하기에 데이터베이스 객체 생성
        BoardDAO bdao = new BoardDAO();
        count = bdao.getAllCount();
 
        // 현재 보여질 페이지 시작 번호를 설정
        int startRow = (currentPage - 1* pageSize + 1;
        int endRow = currentPage * pageSize;
 
        // 최신글 10개를 기준으로 게시글을 리턴 받아주는 메소드 호출
        Vector<BoardBean> v = bdao.getAllBoard(startRow, endRow);
        number = count - (currentPage - 1* pageSize;
 
        // BoardList.jsp 쪽으로 request 객체에 담아서 넘겨준다.
        request.setAttribute("v", v);
        request.setAttribute("number", number);
        request.setAttribute("pageSize", pageSize);
        request.setAttribute("count", count);
        request.setAttribute("currentPage", currentPage);
 
        // BoardList를 통해 forward를 시킨다.
        RequestDispatcher dis = request.getRequestDispatcher("BoardList.jsp");
        dis.forward(request, response);
 
    }
}
 
cs



BoardDAO.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
package model;
 
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 BoardDAO {
 
    Connection con;
    PreparedStatement pstmt;
    ResultSet rs;
 
    // 데이터 베이스에 연결 메소드
    public void getCon() {
        try {
            Context initctx = new InitialContext();
            Context envctx = (Context) initctx.lookup("java:comp/env");
            // 타입이 데이터 소스이므로 데이터소스로 (타입변환해서) 받는다.
            DataSource ds = (DataSource) envctx.lookup("jdbc/pool");
            // 얻은 데이터소스를 사용해 연결한다.
            con = ds.getConnection(); // 커넥션 연결 해주는 메소드
 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    // 전체 게시글의 갯수를 리턴하는 메소드
    public int getAllCount() {
        getCon();
        // 개시글의 갯수를 세야하기 때문에 카운트 변수를 추가하고 초기값을 선언한다.
        int count = 0;
 
        try {
            // sql 쿼리 준비함
            String sql = "select count(*) from board";
            pstmt = con.prepareStatement(sql);
            // ?표가 없으므로 바로 결과실행후 리턴시켜주면 된다.
            rs = pstmt.executeQuery();
            // 전체게시글은 한칸에서 밖에 출력이 되지 않으므로 1칸만 있으면 된다. 반복문 말고 if문으로 사용한다.
            if (rs.next()) { // 데이터가 있다면 카운트에 넣는다.
                // 전체 게시글 수
                count = rs.getInt(1);
            }
            con.close();
 
        } catch (Exception e) {
            e.printStackTrace();
        }
        return count;
    }
 
    // 화면에 보여질 데이터를 10개씩 추출해서 리턴하는 메소드
    public Vector<BoardBean> getAllBoard(int startRow, int endRow) {
        // 리턴할객체 선언
        getCon();
        Vector<BoardBean> v = new Vector<>();
        try {
            // 쿼리 작성
            String sql = "select * from (select A.*, Rownum Rnum from (select * from board order by ref desc, re_step asc)A)"
                    + "where Rnum >= ? and Rnum <= ?";
            // 쿼리 실행할 객체를 선언
            pstmt = con.prepareStatement(sql);
            pstmt.setInt(1, startRow);
            pstmt.setInt(2, endRow);
            // 쿼리실행후 결과 저장
            rs = pstmt.executeQuery();
            // 데이터 개수가 몇개인지 모르기에 반복문을 이용하여 데이터를 추출
            while (rs.next()) {
                // 데이터를 패키징 ( BoardBean 클래스를 이용) 해줌
                BoardBean bean = new BoardBean();
                bean.setNum(rs.getInt(1));
                bean.setWriter(rs.getString(2));
                bean.setEmail(rs.getString(3));
                bean.setSubject(rs.getString(4));
                bean.setPassword(rs.getString(5));
                bean.setReg_date(rs.getDate(6).toString());
                bean.setRef(rs.getInt(7));
                bean.setRe_step(rs.getInt(8));
                bean.setRe_level(rs.getInt(9));
                bean.setReadcount(rs.getInt(10));
                bean.setContent(rs.getString(11));
                // 패키징한 데이터를 벡터에 저장
                v.add(bean);
            }
            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return v;
    }
 
    // 하나의 게시글을 저장하는 메소드 호출
    public void insertBoard(BoardBean bean) {
 
        getCon();
        // 초기값 지정
        int ref = 0;
        int re_step = 1;// 새글이기에
        int re_level = 1;// 새글이기에
 
        try {
            // 쿼리 작성
            // 이 sql에서 1만 더하면 되기때문에 가장큰값을 검색
            String refsql = "select max(ref) from board";
            pstmt = con.prepareStatement(refsql);
            // 쿼리 실행후 결과를 리턴
            rs = pstmt.executeQuery();
            if (rs.next()) {
                ref = rs.getInt(1+ 1// ref가장 큰 값에 1을 더해줌
                // 최신글은 글번호가 가장 크기 때문에 원래 있던 글에서 1을 더해줌
 
            }
            // 데이터를 삽입하는 쿼리
            String sql = "insert into board values(board_seq.NEXTVAL,?,?,?,?,sysdate,?,?,?,0,?)";
            pstmt = con.prepareStatement(sql);
            // ?에 값을 매핑한다.
            pstmt.setString(1, bean.getWriter());
            pstmt.setString(2, bean.getEmail());
            pstmt.setString(3, bean.getSubject());
            pstmt.setString(4, bean.getPassword());
            pstmt.setInt(5, ref);
            pstmt.setInt(6, re_step);
            pstmt.setInt(7, re_level);
            pstmt.setString(8, bean.getContent());
 
            pstmt.executeUpdate();
            con.close();
 
        } catch (Exception e) {
            e.printStackTrace();
        }
 
    }
}
cs



:

19.05.25 jsp 게시판 보기 (model 2 동영상 15강)

Back-End/JSP 2019. 5. 25. 17:45

게시글 카운터링 구현



BoardList.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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
    <center>
        <h2>전체 게시글 보기</h2>
        <table width="700" border="1" bordercolor="skyblue">
            <tr height="40">
                <td colspan="5" align="right">
                    <button onclick="location.href='BoardWriteForm.jsp'">글쓰기</button>
                </td>
            </tr>
 
            <tr height="40">
                <td width="50" align="center">번호</td>
                <td width="320" align="center">제목</td>
                <td width="100" align="center">작성자</td>
                <td width="150" align="center">작성일</td>
                <td width="80" align="center">조회수</td>
            </tr>
            <!-- $안에 number을 사용하면 계속 number만 출력되기 때문에 forEach문으로 number을 계속 1씩 감소시켜야 한다. -->
            <c:set var="number" value="${number}" />
            <c:forEach var="bean" items="${v}">
 
 
                <tr height="40">
                    <td width="50" align="left">${number }</td>
                    <td width="50" align="left">
                        <!-- 들여쓰기 구문 --> <!-- 첫번째 (1) 은 들여쓰기할 필요가 없다. --> <!-- 공백을 여러개 출력하기 위한 구문 -->
                        <c:if test="${bean.re_step > 1 }">
                            <c:forEach var="j" begin="1" end="${(bean.re_step-1)*5}">
                &nbsp;
            </c:forEach>
                        </c:if<!-- 버튼을 눌렀을때 실행이 되게끔 a태그를 건다 --> <a
                        href="BoardInfoControl.do?num=${bean.num }">${bean.subject } </a>
 
                    </td>
                    <td width="50" align="left">${bean.writer }</td>
                    <td width="50" align="left">${bean.reg_date }</td>
                    <td width="50" align="left">${bean.readcount }</td>
                </tr>
                <c:set var="number" value="${number-1 }" />
            </c:forEach>
        </table>
        <p>
            <!-- 페이지 카운터링 소스를 작성한다 -->
            <c:if test="${count > 0 }">
        value = "${count / pageSize +(count%pageSize == 0 ? 0: 1)}";
        <c:set var="startPage" value="${1 }" />
 
                <c:if test="${currentPage %10 != 0 }">
                    <!-- 인트타입으로 변환하기 위해 포장클래스인 integer을 사용한다. -->
                    <!-- 결과를 정수형으로 리턴받아야 하기에 fmt태그를 사용
        fmt는 코어태그가 아니기 때문에 위쪽에서 태그라이브러리를 추가해야한다.-->
                    <fmt:parseNumber var="result" value="${currentPage/10 }"
                        integerOnly="true" />
                    <c:set var="startPage" value="${result*10+1 }" />
                </c:if>
 
                <!-- c:if문은 else를 사용할 수 없기 때문에 이번에는  currentPage %10 == 0 이라는 값을 넣어주어야 한다.-->
 
                <c:if test="${currentPage %10 == 0 }">
                    <!-- 인트타입으로 변환하기 위해 포장클래스인 integer을 사용한다. -->
                    <!-- 결과를 정수형으로 리턴받아야 하기에 fmt태그를 사용
        fmt는 코어태그가 아니기 때문에 위쪽에서 태그라이브러리를 추가해야한다.-->
                    <c:set var="startPage" value="${(result-1)*10+1 }" />
                </c:if>
 
                <!-- 화면에 보여질 페이지 처리 숫자를 표현 -->
                <c:set var="pageBlock" value="${10 }" />
                <c:set var="endPage" value="${startPage+pageBlock-1 }" />
                <c:if test="${endPage > pageCount }">
                    <c:set var="endPage" value="${pageCount }" />
                </c:if>
 
                <!-- 10보다 페이지가 크면 "이전" 이라는 링크를 걸지 파악하는 구문 (if)-->
                <c:if test="${startPage > 10 }">
                    <a href='BoardListCon.do?pageNum=${startPage-10 }'>[이전]</a>
                </c:if>
 
                <!-- 페이징 처리 -->
                <c:forEach var="i" begin="${startPage }" end="${endPage }">
                    <a href='BoardListCon.do?pageNum=${i}'>[${i}]</a>
                </c:forEach>
 
                <!-- 다음 -->
                <c:if test="${endPage<pageCount}">
                    <a href='BoardListCon.do?pageNum=${startPage+10 }'>[다음]</a>
                </c:if>
            </c:if>
    </center>
</body>
</html>
 
cs




:

19.05.24 게시판 보기 (model 2 동영상 12강~14강)

Back-End/JSP 2019. 5. 24. 17:23


-model 2 방식으로 게시판 전체 글보기-


model 1 방식때는 게시글, 전체글보기를 jsp로 구현했고,

model 2 방식은 컨트롤러 클래스 (서블릿) 가 구현

서블릿이 전체글이 담긴 DAO와 연결되서 데이터를 액세스(빈클래스 사용)하고 빈클래스에서 나온값을 벡터에 담고

다시 서블릿으로 가져와 JSP 에 넘겨서 글 보기가 가능하게 한다.

즉, 서블릿에서 처리하고 결과만 JSP에서 출력함


  1. 커넥션 풀 설정


  2. DAO (DB연결) 만들기


  3. 빈클래스 만들기


  4. 서블릿 클래스 (컨트롤러) 만들기





BoardListCon.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
package control;
 
import java.io.IOException;
import java.util.Vector;
 
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;
 
import model.BoardBean;
import model.BoardDAO;
 
/**
 * Servlet implementation class BoardListCon
 */

//@WebServilet는 서블릿 클래스의 요청을 위한 url 매핑을 보다 쉽게 자바 클래스에서

 설정할 수 있도록 제공되는 어노테이션 이다. 

//웹 서블릿 url 설정 

//url을  /BoadrListCon.do를 요청했을때 BoadrListCon.do가 호출이 된다.

 

@WebServlet("/BoardListCon.do")
public class BoardListCon extends HttpServlet {
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        reqPro(request, response);
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        reqPro(request, response);
    }
 
    protected void reqPro(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // jsp쪽에서 출력되게끔 자료를 넘겨주어야 한다.
 
        // 화면에 보여질 게시글의 개수를 지정
        int pageSize = 10;
 
        // 현재 보여지고 있는 페이지의 넘버값을 읽어들인다.
        String pageNum = request.getParameter("pageNum");
 
        // null 처리
        if (pageNum == null) {
            pageNum = "1";
        }
        // 전체 게시글의 갯수
        int count = 0;
        // jsp 페이지 내에서 보여질 넘버링 숫자값을 저장하는 변수 선언
        int number = 0;
 
        // 현재 보여지고 있는 페이지 문자를 숫자로 변환
        int currentPage = Integer.parseInt(pageNum);
        // 전체 게시글의 갯수를 가져와야 하기에 데이터베이스 객체 생성
        BoardDAO bdao = new BoardDAO();
        count = bdao.getAllCount();
 
        // 현재 보여질 페이지 시작 번호를 설정
        int startRow = (currentPage - 1* pageSize + 1;
        int endRow = currentPage * pageSize;
 
        // 최신글 10개를 기준으로 게시글을 리턴 받아주는 메소드 호출
        Vector<BoardBean> v = bdao.getAllBoard(startRow, endRow);
        number = count - (currentPage - 1* pageSize;
 
        // BoardList.jsp 쪽으로 request 객체에 담아서 넘겨준다.
        request.setAttribute("v", v);
        request.setAttribute("number", number);
        request.setAttribute("pageSize", pageSize);
        request.setAttribute("count", count);
        request.setAttribute("currentPage", currentPage);
 
        // BoardList를 통해 forward를 시킨다.
        RequestDispatcher dis = request.getRequestDispatcher("BoardList.jsp");
        dis.forward(request, response);
 
    }
}
 
cs


BoardBean.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
98
99
100
101
102
103
104
105
package model;
 
public class BoardBean { // 빈클래스 생성
 
    private int num;
    private String email;
    private String subject;
    private String password;
    private String reg_date;
    private String writer;
    private int ref;
    private int re_step;
    private int re_level;
    private int readcount;
    private String content;
 
    public int getNum() {
        return num;
    }
 
    public void setNum(int num) {
        this.num = num;
    }
 
    public String getEmail() {
        return email;
    }
 
    public void setEmail(String email) {
        this.email = email;
    }
 
    public String getSubject() {
        return subject;
    }
 
    public void setSubject(String subject) {
        this.subject = subject;
    }
 
    public String getPassword() {
        return password;
    }
 
    public void setPassword(String password) {
        this.password = password;
    }
 
    public String getReg_date() {
        return reg_date;
    }
 
    public void setReg_date(String reg_date) {
        this.reg_date = reg_date;
    }
 
    public String getWriter() {
        return writer;
    }
 
    public void setWriter(String writer) {
        this.writer = writer;
    }
 
    public int getRef() {
        return ref;
    }
 
    public void setRef(int ref) {
        this.ref = ref;
    }
 
    public int getRe_step() {
        return re_step;
    }
 
    public void setRe_step(int re_step) {
        this.re_step = re_step;
    }
 
    public int getRe_level() {
        return re_level;
    }
 
    public void setRe_level(int re_level) {
        this.re_level = re_level;
    }
 
    public int getReadcount() {
        return readcount;
    }
 
    public void setReadcount(int readcount) {
        this.readcount = readcount;
    }
 
    public String getContent() {
        return content;
    }
 
    public void setContent(String content) {
        this.content = content;
    }
 
}
cs



BoardDAO.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
package model;
 
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 BoardDAO {
 
    Connection con;
    PreparedStatement pstmt;
    ResultSet rs;
 
    // 데이터 베이스에 연결 메소드
    public void getCon() {
        try {
            Context initctx = new InitialContext();
            Context envctx = (Context) initctx.lookup("java:comp/env");
            // 타입이 데이터 소스이므로 데이터소스로 (타입변환해서) 받는다.
            DataSource ds = (DataSource) envctx.lookup("jdbc/pool");
            // 얻은 데이터소스를 사용해 연결한다.
            con = ds.getConnection(); // 커넥션 연결 해주는 메소드
 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    // 전체 게시글의 갯수를 리턴하는 메소드
    public int getAllCount() {
        getCon();
        // 개시글의 갯수를 세야하기 때문에 카운트 변수를 추가하고 초기값을 선언한다.
        int count = 0;
 
        try {
            // sql 쿼리 준비함
            String sql = "select count(*) from board";
            pstmt = con.prepareStatement(sql);
            // ?표가 없으므로 바로 결과실행후 리턴시켜주면 된다.
            rs = pstmt.executeQuery();
            // 전체게시글은 한칸에서 밖에 출력이 되지 않으므로 1칸만 있으면 된다. 반복문 말고 if문으로 사용한다.
            if (rs.next()) { // 데이터가 있다면 카운트에 넣는다.
                // 전체 게시글 수
                count = rs.getInt(1);
            }
            con.close();
 
        } catch (Exception e) {
            e.printStackTrace();
        }
        return count;
    }
 
    // 화면에 보여질 데이터를 10개씩 추출해서 리턴하는 메소드
    public Vector<BoardBean> getAllBoard(int startRow, int endRow) {
        // 리턴할객체 선언
        getCon();
        Vector<BoardBean> v = new Vector<>();
        try {
            // 쿼리 작성
            String sql = "select * from (select A.*, Rownum Rnum from (select * from board order by ref desc, re_step asc)A)"
                    + "where Rnum >= ? and Rnum <= ?";
            // 쿼리 실행할 객체를 선언
            pstmt = con.prepareStatement(sql);
            pstmt.setInt(1, startRow);
            pstmt.setInt(2, endRow);
            // 쿼리실행후 결과 저장
            rs = pstmt.executeQuery();
            // 데이터 개수가 몇개인지 모르기에 반복문을 이용하여 데이터를 추출
            while (rs.next()) {
                // 데이터를 패키징 ( BoardBean 클래스를 이용) 해줌
                BoardBean bean = new BoardBean();
                bean.setNum(rs.getInt(1));
                bean.setWriter(rs.getString(2));
                bean.setEmail(rs.getString(3));
                bean.setSubject(rs.getString(4));
                bean.setPassword(rs.getString(5));
                bean.setReg_date(rs.getDate(6).toString());
                bean.setRef(rs.getInt(7));
                bean.setRe_step(rs.getInt(8));
                bean.setRe_level(rs.getInt(9));
                bean.setReadcount(rs.getInt(10));
                bean.setContent(rs.getString(11));
                // 패키징한 데이터를 벡터에 저장
                v.add(bean);
            }
            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return v;
    }
 
}
 
cs



BoardList.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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
    <center>
        <h2>전체 게시글 보기</h2>
        <table width="700" border="1" bordercolor="skyblue">
            <tr height="40">
                <td colspan="5" align="right">
                    <button onclick="location.href='BoardWriteForm.jsp'">글쓰기</button>
                </td>
            </tr>
 
            <tr height="40">
                <td width="50" align="center">번호</td>
                <td width="320" align="center">제목</td>
                <td width="100" align="center">작성자</td>
                <td width="150" align="center">작성일</td>
                <td width="80" align="center">조회수</td>
            </tr>
            <!-- $안에 number을 사용하면 계속 number만 출력되기 때문에 forEach문으로 number을 계속 1씩 감소시켜야 한다. -->
            <c:set var="number" value="${number}" />
            <c:forEach var="bean" items="${v}">
 
 
                <tr height="40">
                    <td width="50" align="left">${number }</td>
                    <td width="50" align="left">
                        <!-- 들여쓰기 구문 --> <!-- 첫번째 (1) 은 들여쓰기할 필요가 없다. --> <!-- 공백을 여러개 출력하기 위한 구문 -->
                        <c:if test="${bean.re_step > 1 }">
                            <c:forEach var="j" begin="1" end="${(bean.re_step-1)*5}">
                &nbsp;
            </c:forEach>
                        </c:if<!-- 버튼을 눌렀을때 실행이 되게끔 a태그를 건다 --> <a
                        href="BoardInfoControl.do?num=${bean.num }">${bean.subject } </a>
 
                    </td>
                    <td width="50" align="left">${bean.writer }</td>
                    <td width="50" align="left">${bean.reg_date }</td>
                    <td width="50" align="left">${bean.readcount }</td>
                </tr>
                <c:set var="number" value="${number-1 }" />
            </c:forEach>
        </table>
 
    </center>
</body>
</html>
cs



: