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



: