본문으로 바로가기

[JSP개발] 게시판 - 답글달기

category 코딩/JSP 2016. 12. 16. 15:42







1. 개요







상세보기 구현 후 이번에는 답변 글을 구현할 것이다. 여기서 구현하는 답글의 경우 최근 답글이 위로 오도록 한 형태이다. 답글 작성의 전체적인 흐름은 다음과 같다.


상세보기 화면에서 답글 버튼 클릭 → 답글 작성 화면으로 이동 → 답글 작성 후 등록버튼 클릭 → 원래의 글 목록으로 이동


이를 JSP와 Java로 보면 이런식으로 나타난다.


BoardDetailForm.jsp → BoardReplyFormAction.java → BoardReplyForm.jsp → BoardReplyAction.java (BoardDAO에서 답글저장) → BoardListAction.java → BoardListForm.jsp



답변형 게시판에 대해 추가적인 정보는 아래의 링크를 통해 확인 가능하다. 


■ 답변글의 최근 답글이 아래로 오도록 구현(현재 포스팅과 반대방법)


■ 오라클 계층형 쿼리를 이용한 답변형 게시판



 JSP

  • BoardReplyForm.jsp : 답변 글 작성 화면이다.

  • BoardDetailForm.jsp : 상세보기 화면이다. 답글은 로그인한 유저만 작성할 수 있도록 수정하였다.

  • BoardListForm.jsp : 글 목록 화면이다. 답변 글의 경우 글 제목 앞에 공백과 RE : 가 들어가도록 처리하였다.


 Java

  • BoardReplyFormAction.java : 답변 글 작성 화면으로 이동하는 Action이다.

  • BoardReplyAction.java : 답변 글을 작성하는 Action이다.




2. 소스 코드



■ BoardCommand.properties


1
2
3
4
5
6
7
8
9
10
11
12
13
# Form Change
BoardWriteForm.bo=jsp.board.action.BoardFormChangeAction
BoardListForm.bo=jsp.board.action.BoardFormChangeAction
BoardDetailForm.bo=jsp.board.action.BoardFormChangeAction
BoardReplyForm.bo=jsp.board.action.BoardFormChangeAction
 
# Action
BoardWriteAction.bo=jsp.board.action.BoardWriteAction
BoardListAction.bo=jsp.board.action.BoardListAction
BoardDetailAction.bo=jsp.board.action.BoardDetailAction
FileDownloadAction.bo=jsp.board.action.FileDownloadAction
BoardReplyFormAction.bo=jsp.board.action.BoardReplyFormAction
BoardReplyAction.bo=jsp.board.action.BoardReplyAction
cs



■ BoardDetailForm.jsp 




상세보기 화면에서는 로그인을 해야만 답글을 달 수 있도록 처리하였다. 수정, 삭제 버튼의 경우 글 작성자일 경우만 보이도록 처리했다.




답글 버튼을 누를 경우 스크립트에서 32줄이 실행된다. 이때 현재 게시글 번호와 페이지 번호를 같이 전송한다. 게시글 번호는 답글을 달려고 하는 원본 글, 즉 부모 글의 정보를 얻기 위해 필요하다. 페이지 번호는 답글 작성후 원래의 페이지로 돌아오게 하기 위해 필요하다.



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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>  
 
<html>
<head>
    <title>글 상세보기</title>
    
    <style type="text/css">
        #wrap {
            width: 800px;
            margin: 0 auto 0 auto;
        }
    
        #detailBoard{
            text-align :center;
        }
        
        #title{
            height : 16;
            font-family :'돋움';
            font-size : 12;
            text-align :center;
        }
    </style>
    
    <script type="text/javascript">
        function changeView(value)
        {
            if(value == 0)    location.href="BoardListAction.bo?page=${pageNum}";
            else if(value == 1){
                location.href='BoardReplyFormAction.bo?num=${board.board_num}&page=${pageNum}';
            }
                
        }
    </script>
</head>
<body>
 
<div id="wrap">
    <br><br>
    <div id="board">
        <table id="detailBoard" width="800" border="3" bordercolor="lightgray">
        
            <tr>
                <td id="title">작성일</td>
                <td>${board.board_date}</td>
            </tr>
            <tr>
                <td id="title">작성자</td>
                <td>${board.board_id}</td>
            </tr>
            <tr>
                <td id="title">
                    제 목
                </td>
                <td>
                    ${board.board_subject}
                </td>        
            </tr>
            <tr>
                <td id="title">
                    내 용
                </td>
                <td>
                    ${board.board_content}
                </td>        
            </tr>
            <tr>
                <td id="title">
                    첨부파일
                </td>
                <td>
                    <a href='FileDownloadAction.bo?file_name=${board.board_file}'>${board.board_file}</a>
                </td>    
            </tr>
    
            <tr align="center" valign="middle">
                <td colspan="5">
                <c:if test="${sessionScope.sessionID !=null}">
                    <c:if test="${sessionScope.sessionID == board.board_id}">
                        <input type="button" value="수정" >
                        <input type="button" value="삭제" >
                    </c:if>
                        <input type="button" value="답글" onclick="changeView(1)" >
                </c:if>        
                    <input type="button" value="목록" onclick="changeView(0)">            
                </td> <!-- javascript:location.href='BoardListAction.bo?page=${pageNum}' -->
            </tr>
        </table>
    </div>
</div>    
 
</body>
</html>
cs



■ BoardReplyFormAction.java 


BoardReplyFormAction는 상세 보기에서 답글 버튼 클릭 시 답글 작성 화면으로 이동할 때 실행되는 Action이다.




넘겨받은 게시글 번호를 이용해 부모 글의 정보를 BoardBean에 담아서 가져온다. (25줄) 그리고 부모 글 정보와 페이지 번호를 request에 세팅한다.


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
package jsp.board.action;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import jsp.board.model.BoardBean;
import jsp.board.model.BoardDAO;
import jsp.common.action.Action;
import jsp.common.action.ActionForward;
 
public class BoardReplyFormAction implements Action
{
    @Override
    public ActionForward execute(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        
        ActionForward forward = new ActionForward();
        
        BoardDAO dao = BoardDAO.getInstance();
        int num = Integer.parseInt(request.getParameter("num"));
        // 답글 작성 후 원래 페이지로 돌아가기 위해 페이지 번호가 필요하다.
        String pageNum = request.getParameter("page");
        
        BoardBean board = dao.getDetail(num);
        request.setAttribute("board", board);
        request.setAttribute("page", pageNum);
        
        forward.setRedirect(false); // 단순한 조회이므로
        forward.setNextPath("BoardReplyForm.bo");
        
        return forward;
    }
}
cs



■ BoardReplyForm.jsp


답글 작성 화면이다.




답글을 작성할 때 BoardReplyFormAction에서 넘겨받은 부모 글의 그룹번호, 답글 레벨, 답글 순서 정보를 넘겨준다. 그리고 페이지 번호도 같이 전달하는데 답글 작성 후 글 목록으로 돌아갈 때 원래 있던 페이지로 이동하기 위해서이다.



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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<html>
<head>
    <title>게시판 - 답변글</title>
    
    <style type="text/css">
        #title{
            height : 16;
            font-family :'돋움';
            font-size : 12;
            text-align :center;
        }
    </style>
    
</head>
<body>
 
    <br>
    <b><font size="6" color="gray">답글 작성</font></b>
    <br>
    
    <form method="post" action="BoardReplyAction.bo?page=${page}" name="boardForm">
    
    <input type="hidden" name="board_id" value="${sessionScope.sessionID}">
    <input type="hidden" name="board_num" value="${board.board_num}"/>
    <input type="hidden" name="board_re_ref" value="${board.board_re_ref}"/>
    <input type="hidden" name="board_re_lev" value="${board.board_re_lev}"/>
    <input type="hidden" name="board_re_seq" value="${board.board_re_seq}"/>
 
    <table width="700" border="3" bordercolor="lightgray" align="center">
        <tr>
            <td id="title">작성자</td>
            <td>${sessionScope.sessionID}</td>
        </tr>
            <tr>
            <td id="title">
                제 목
            </td>
            <td>
                <input name="board_subject" type="text" size="70" maxlength="100" value=""/>
            </td>        
        </tr>
        <tr>
            <td id="title">
                내 용
            </td>
            <td>
                <textarea name="board_content" cols="72" rows="20">
                </textarea>            
            </td>        
        </tr>
 
        <tr align="center" valign="middle">
            <td colspan="5">
                <input type="reset" value="작성취소" >
                <input type="submit" value="등록" >
                <input type="button" value="목록" onclick="javascript:history.go(-1)">            
            </td>
        </tr>
    </table>    
    </form>
    
</body>
</html>
cs



■ BoardReplyAction.java


답글 작성을 처리하는 Action이다. BoardReplyForm.jsp에서 등록 버튼을 누를 시 실행된다.




넘겨받은 페이지 번호를 가져온다.




답글의 정보(답글 작성자, 답글 제목, 답글 내용) 및 답글에 필요한 부모글의 그룹번호, 답글 레벨, 답글 순서를 가져와서 변수에 담는다.




먼저 그룹 번호(board_re_ref)와 답글 순서(board_re_seq)만 BoardBean에 담아서 dao의 updateReSeq( ) 메서드로 전달한다. 이 작업을 하는 이유는 답글에서 최근 달린 답글이 위로 오도록 하기 위해서이다.




updateReSeq( ) 메서드를 실행하고는 답글의 정보를 BoardBean에 담아 dao로 전달하여 저장한다.




글 목록에서 원래 있던 페이지로 이동하기 위해 페이지 번호를 파라미터 값으로 전달한다.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package jsp.board.action;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import jsp.board.model.BoardBean;
import jsp.board.model.BoardDAO;
import jsp.common.action.Action;
import jsp.common.action.ActionForward;
 
public class BoardReplyAction implements Action
{
    @Override
    public ActionForward execute(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        
        request.setCharacterEncoding("euc-kr");
        ActionForward forward = new ActionForward();
        
        BoardDAO dao = BoardDAO.getInstance();
        BoardBean borderData = new BoardBean();
        
        // 답글 작성 후 원래 페이지로 돌아가기 위해 페이지 번호가 필요하다.
        String pageNum = request.getParameter("page");
        
        // 파리미터 값을 가져온다.
        String id = request.getParameter("board_id");
        String subject = request.getParameter("board_subject");
        String content = request.getParameter("board_content");
        int ref = Integer.parseInt(request.getParameter("board_re_ref"));
        int lev = Integer.parseInt(request.getParameter("board_re_lev"));
        int seq = Integer.parseInt(request.getParameter("board_re_seq"));
        
        // 답글중 가장 최근 답글이 위로 올라가게 처리한다. 
        // 그러기 위해 답글의 순서인 seq를 1증가시킨다.
        borderData.setBoard_re_ref(ref);
        borderData.setBoard_re_seq(seq);
        dao.updateReSeq(borderData);
        
        // 답글 저장
        borderData.setBoard_num(dao.getSeq()); // 답글의 글번호는 시퀀스값 가져와 세팅
        borderData.setBoard_id(id);
        borderData.setBoard_subject(subject);
        borderData.setBoard_content(content);
        borderData.setBoard_re_ref(ref);
        borderData.setBoard_re_lev(lev+1);
        borderData.setBoard_re_seq(seq+1);
        
        boolean result = dao.boardInsert(borderData);
        
        if(result){
            forward.setRedirect(false); 
            // 원래있던 페이지로 돌아가기 위해 페이지번호를 전달한다.
            forward.setNextPath("BoardListAction.bo?page="+pageNum); 
        }
        return forward;
    }
}
cs



■ BoardDAO.java


BoardDAO에서는 답글 순서를 처리하는 updateReSeq( ) 메서드를 추가하였다. 그리고 답글도 저장하기 위해 boardInsert( ) 메서드를 수정하였다.




boardInsert( )에서는 board_re_seq(답글 순서) 값이 0인 경우에 따라 처리를 달리하도록 했다. board_re_seq 값이 0이라는 것은 답글이 없는 상태이므로 부모글을 나타낸다. 이럴 때는 그룹 번호로 시퀀스 값을 사용하면 된다. 


board_re_seq 값이 0이 아닐 경우는 답변글을 의미하므로 그룹 번호는 부모글의 글 번호를 집어넣도록 한다.




updateReSeq( )의 쿼리이다. 이 부분은 최근 작성한 답글이 위로 오게 처리한 부분이다. 



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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
package jsp.board.model;
 
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
 
import jsp.common.util.DBConnection;
 
 
public class BoardDAO 
{
    private Connection conn;
    private PreparedStatement pstmt;
    private ResultSet rs;
    
    private static BoardDAO instance;
    
    private BoardDAO(){}
    public static BoardDAO getInstance(){
        if(instance==null)
            instance=new BoardDAO();
        return instance;
    }
    
    // 시퀀스를 가져온다.
    public int getSeq()
    {
        int result = 1;
        
        try {
            conn = DBConnection.getConnection();
            
            // 시퀀스 값을 가져온다. (DUAL : 시퀀스 값을 가져오기위한 임시 테이블)
            StringBuffer sql = new StringBuffer();
            sql.append("SELECT BOARD_NUM.NEXTVAL FROM DUAL");
            
            pstmt = conn.prepareStatement(sql.toString());
            // 쿼리 실행
            rs = pstmt.executeQuery();
            
            if(rs.next())    result = rs.getInt(1);
 
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        
        close();
        return result;    
    } // end getSeq
    
    // 글 삽입
    public boolean boardInsert(BoardBean board)
    {
        boolean result = false;
        
        try {
            conn = DBConnection.getConnection();
            
            // 자동 커밋을 false로 한다.
            conn.setAutoCommit(false);
            
            StringBuffer sql = new StringBuffer();
            sql.append("INSERT INTO MEMBER_BOARD");
            sql.append("(BOARD_NUM, BOARD_ID, BOARD_SUBJECT, BOARD_CONTENT, BOARD_FILE");
            sql.append(", BOARD_RE_REF, BOARD_RE_LEV, BOARD_RE_SEQ, BOARD_COUNT, BOARD_DATE)");
            sql.append(" VALUES(?,?,?,?,?,?,?,?,?,sysdate)");
 
            // 시퀀스 값을 글번호와 그룹번호로 사용
            int num = board.getBoard_num();
 
            pstmt = conn.prepareStatement(sql.toString());
            pstmt.setInt(1, num);
            pstmt.setString(2, board.getBoard_id());
            pstmt.setString(3, board.getBoard_subject());
            pstmt.setString(4, board.getBoard_content());
            pstmt.setString(5, board.getBoard_file());
            
            if(board.getBoard_re_seq()==0// re_seq==0 은 답변글이 없는경우, 즉 부모글일경우    
                pstmt.setInt(6, num);    
            else
                pstmt.setInt(6, board.getBoard_re_ref());
 
            pstmt.setInt(7, board.getBoard_re_lev());
            pstmt.setInt(8, board.getBoard_re_seq());
            pstmt.setInt(90);
 
            int flag = pstmt.executeUpdate();
            if(flag > 0){
                result = true;
                // 완료시 커밋
                conn.commit(); 
            }
            
        } catch (Exception e) {
            try {
                conn.rollback();
            } catch (SQLException sqle) {
                sqle.printStackTrace();
            } 
            throw new RuntimeException(e.getMessage());
        }
        
        close();
        return result;    
    } // end boardInsert();
    
    
    // 글목록 가져오기
    public ArrayList<BoardBean> getBoardList(HashMap<String, Object> listOpt)
    {
        ArrayList<BoardBean> list = new ArrayList<BoardBean>();
        
        String opt = (String)listOpt.get("opt");
        String condition = (String)listOpt.get("condition");
        int start = (Integer)listOpt.get("start");
        
        try {
            conn = DBConnection.getConnection();
            StringBuffer sql = new StringBuffer();
            
            // 글목록 전체를 보여줄 때
            if(opt == null)
            {
                // BOARD_RE_REF(그룹번호)의 내림차순 정렬 후 동일한 그룹번호일 때는
                // BOARD_NUM(글번호)의 오름차순으로 정렬 한 후에
                // start번 째 부터 start+9까지(10개의 글을 한 목록에 보여주기 위해)의 
                // 데이터를 검색해주는 sql
                // desc : 내림차순, asc : 오름차순 ( 생략 가능 )
                sql.append("select * from ");
                sql.append("(select rownum rnum, BOARD_NUM, BOARD_ID, BOARD_SUBJECT");
                sql.append(", BOARD_CONTENT, BOARD_FILE, BOARD_COUNT, BOARD_RE_REF");
                sql.append(", BOARD_RE_LEV, BOARD_RE_SEQ, BOARD_DATE ");
                sql.append("FROM");
                sql.append(" (select * from MEMBER_BOARD order by BOARD_RE_REF desc, BOARD_RE_SEQ asc)) ");
                sql.append("where rnum>=? and rnum<=?");
                
                pstmt = conn.prepareStatement(sql.toString());
                pstmt.setInt(1, start);
                pstmt.setInt(2, start+9);
                
                // StringBuffer를 비운다.
                sql.delete(0, sql.toString().length());
            }
            else if(opt.equals("0")) // 제목으로 검색
            {
                sql.append("select * from ");
                sql.append("(select rownum rnum, BOARD_NUM, BOARD_ID, BOARD_SUBJECT");
                sql.append(", BOARD_CONTENT, BOARD_FILE, BOARD_DATE, BOARD_COUNT");
                sql.append(", BOARD_RE_REF, BOARD_RE_LEV, BOARD_RE_SEQ ");
                sql.append("FROM ");
                sql.append("(select * from MEMBER_BOARD where BOARD_SUBJECT like ? ");
                sql.append("order BY BOARD_RE_REF desc, BOARD_RE_SEQ asc)) ");
                sql.append("where rnum>=? and rnum<=?");
                
                pstmt = conn.prepareStatement(sql.toString());
                pstmt.setString(1"%"+condition+"%");
                pstmt.setInt(2, start);
                pstmt.setInt(3, start+9);
                
                sql.delete(0, sql.toString().length());
            }
            else if(opt.equals("1")) // 내용으로 검색
            {
                sql.append("select * from ");
                sql.append("(select rownum rnum, BOARD_NUM, BOARD_ID, BOARD_SUBJECT");
                sql.append(", BOARD_CONTENT, BOARD_FILE, BOARD_DATE, BOARD_COUNT");
                sql.append(", BOARD_RE_REF, BOARD_RE_LEV, BOARD_RE_SEQ ");
                sql.append("FROM ");
                sql.append("(select * from MEMBER_BOARD where BOARD_CONTENT like ? ");
                sql.append("order BY BOARD_RE_REF desc, BOARD_RE_SEQ asc)) ");
                sql.append("where rnum>=? and rnum<=?");
                
                pstmt = conn.prepareStatement(sql.toString());
                pstmt.setString(1"%"+condition+"%");
                pstmt.setInt(2, start);
                pstmt.setInt(3, start+9);
                
                sql.delete(0, sql.toString().length());
            }
            else if(opt.equals("2")) // 제목+내용으로 검색
            {
                sql.append("select * from ");
                sql.append("(select rownum rnum, BOARD_NUM, BOARD_ID, BOARD_SUBJECT");
                sql.append(", BOARD_CONTENT, BOARD_FILE, BOARD_DATE, BOARD_COUNT");
                sql.append(", BOARD_RE_REF, BOARD_RE_LEV, BOARD_RE_SEQ ");
                sql.append("FROM ");
                sql.append("(select * from MEMBER_BOARD where BOARD_SUBJECT like ? OR BOARD_CONTENT like ? ");
                sql.append("order BY BOARD_RE_REF desc, BOARD_RE_SEQ asc)) ");
                sql.append("where rnum>=? and rnum<=?");
                
                pstmt = conn.prepareStatement(sql.toString());
                pstmt.setString(1"%"+condition+"%");
                pstmt.setString(2"%"+condition+"%");
                pstmt.setInt(3, start);
                pstmt.setInt(4, start+9);
                
                sql.delete(0, sql.toString().length());
            }
            else if(opt.equals("3")) // 글쓴이로 검색
            {
                sql.append("select * from ");
                sql.append("(select rownum rnum, BOARD_NUM, BOARD_ID, BOARD_SUBJECT");
                sql.append(", BOARD_CONTENT, BOARD_FILE, BOARD_DATE, BOARD_COUNT");
                sql.append(", BOARD_RE_REF, BOARD_RE_LEV, BOARD_RE_SEQ ");
                sql.append("FROM ");
                sql.append("(select * from MEMBER_BOARD where BOARD_ID like ? ");
                sql.append("order BY BOARD_RE_REF desc, BOARD_RE_SEQ asc)) ");
                sql.append("where rnum>=? and rnum<=?");
                
                pstmt = conn.prepareStatement(sql.toString());
                pstmt.setString(1"%"+condition+"%");
                pstmt.setInt(2, start);
                pstmt.setInt(3, start+9);
                
                sql.delete(0, sql.toString().length());
            }
            
            rs = pstmt.executeQuery();
            while(rs.next())
            {
                BoardBean board = new BoardBean();
                board.setBoard_num(rs.getInt("BOARD_NUM"));
                board.setBoard_id(rs.getString("BOARD_ID"));
                board.setBoard_subject(rs.getString("BOARD_SUBJECT"));
                board.setBoard_content(rs.getString("BOARD_CONTENT"));
                board.setBoard_file(rs.getString("BOARD_FILE"));
                board.setBoard_count(rs.getInt("BOARD_COUNT"));
                board.setBoard_re_ref(rs.getInt("BOARD_RE_REF"));
                board.setBoard_re_lev(rs.getInt("BOARD_RE_LEV"));
                board.setBoard_re_seq(rs.getInt("BOARD_RE_SEQ"));
                board.setBoard_date(rs.getDate("BOARD_DATE"));
                list.add(board);
            }
            
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        
        close();
        return list;
    } // end getBoardList
    
    // 글의 개수를 가져오는 메서드
    public int getBoardListCount(HashMap<String, Object> listOpt)
    {
        int result = 0;
        String opt = (String)listOpt.get("opt");
        String condition = (String)listOpt.get("condition");
        
        try {
            conn = DBConnection.getConnection();
            StringBuffer sql = new StringBuffer();
            
            if(opt == null)    // 전체글의 개수
            {
                sql.append("select count(*) from MEMBER_BOARD");
                pstmt = conn.prepareStatement(sql.toString());
                
                // StringBuffer를 비운다.
                sql.delete(0, sql.toString().length());
            }
            else if(opt.equals("0")) // 제목으로 검색한 글의 개수
            {
                sql.append("select count(*) from MEMBER_BOARD where BOARD_SUBJECT like ?");
                pstmt = conn.prepareStatement(sql.toString());
                pstmt.setString(1'%'+condition+'%');
                
                sql.delete(0, sql.toString().length());
            }
            else if(opt.equals("1")) // 내용으로 검색한 글의 개수
            {
                sql.append("select count(*) from MEMBER_BOARD where BOARD_CONTENT like ?");
                pstmt = conn.prepareStatement(sql.toString());
                pstmt.setString(1'%'+condition+'%');
                
                sql.delete(0, sql.toString().length());
            }
            else if(opt.equals("2")) // 제목+내용으로 검색한 글의 개수
            {
                sql.append("select count(*) from MEMBER_BOARD ");
                sql.append("where BOARD_SUBJECT like ? or BOARD_CONTENT like ?");
                pstmt = conn.prepareStatement(sql.toString());
                pstmt.setString(1'%'+condition+'%');
                pstmt.setString(2'%'+condition+'%');
                
                sql.delete(0, sql.toString().length());
            }
            else if(opt.equals("3")) // 글쓴이로 검색한 글의 개수
            {
                sql.append("select count(*) from MEMBER_BOARD where BOARD_ID like ?");
                pstmt = conn.prepareStatement(sql.toString());
                pstmt.setString(1'%'+condition+'%');
                
                sql.delete(0, sql.toString().length());
            }
            
            rs = pstmt.executeQuery();
            if(rs.next())    result = rs.getInt(1);
            
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        
        close();
        return result;
    } // end getBoardListCount
    
    
    // 상세보기
    public BoardBean getDetail(int boardNum)
    {    
        BoardBean board = null;
        
        try {
            conn = DBConnection.getConnection();
            
            StringBuffer sql = new StringBuffer();
            sql.append("select * from MEMBER_BOARD where BOARD_NUM = ?");
            
            pstmt = conn.prepareStatement(sql.toString());
            pstmt.setInt(1, boardNum);
            
            rs = pstmt.executeQuery();
            if(rs.next())
            {
                board = new BoardBean();
                board.setBoard_num(boardNum);
                board.setBoard_id(rs.getString("BOARD_ID"));
                board.setBoard_subject(rs.getString("BOARD_SUBJECT"));
                board.setBoard_content(rs.getString("BOARD_CONTENT"));
                board.setBoard_file(rs.getString("BOARD_FILE"));
                board.setBoard_count(rs.getInt("BOARD_COUNT"));
                board.setBoard_re_ref(rs.getInt("BOARD_RE_REF"));
                board.setBoard_re_lev(rs.getInt("BOARD_RE_LEV"));
                board.setBoard_re_seq(rs.getInt("BOARD_RE_SEQ"));
                board.setBoard_date(rs.getDate("BOARD_DATE"));
            }
            
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        
        close();
        return board;
    } // end getDetail()
    
    // 조회수 증가
    public boolean updateCount(int boardNum)
    {
        boolean result = false;
        
        try {
            conn = DBConnection.getConnection();
            
            // 자동 커밋을 false로 한다.
            conn.setAutoCommit(false);
            
            StringBuffer sql = new StringBuffer();
            sql.append("update MEMBER_BOARD set BOARD_COUNT = BOARD_COUNT+1 ");
            sql.append("where BOARD_NUM = ?");
            
            pstmt = conn.prepareStatement(sql.toString());
            pstmt.setInt(1, boardNum);
            
            int flag = pstmt.executeUpdate();
            if(flag > 0){
                result = true;
                conn.commit(); // 완료시 커밋
            }    
        } catch (Exception e) {
            try {
                conn.rollback(); // 오류시 롤백
            } catch (SQLException sqle) {
                sqle.printStackTrace();
            }
            throw new RuntimeException(e.getMessage());
        }
        
        close();
        return result;
    } // end updateCount
    
    
    
    public boolean updateReSeq(BoardBean board)
    {
        boolean result = false;
        
        int ref = board.getBoard_re_ref();     // 원본글 번호(그룹번호)
        int seq = board.getBoard_re_seq();     // 답변글의 순서
        
        try {    
            StringBuffer sql = new StringBuffer();
            
            conn = DBConnection.getConnection();
            conn.setAutoCommit(false); // 자동 커밋을 false로 한다.
            
            // ref(그룹번호)와 seq(답글순서)을 확인하여 원본 글에 다른 답변 글이 있으면, 
            // 답변 글 중 답변 글보다 상위에 있는 글의 seq보다 높은 글의 seq값을 1씩 증가시킨다.
            sql.append("update MEMBER_BOARD set BOARD_RE_SEQ = BOARD_RE_SEQ+1 ");
            sql.append("where BOARD_RE_REF = ? and BOARD_RE_SEQ > ?");
            
            pstmt = conn.prepareStatement(sql.toString());
            pstmt.setInt(1, ref);
            pstmt.setInt(2, seq);
            
            int flag = pstmt.executeUpdate();
            if(flag > 0){
                result = true;
                conn.commit(); // 완료시 커밋
            }
            
        } catch (Exception e) {
            try {
                conn.rollback(); // 오류시 롤백
            } catch (SQLException sqle) {
                sqle.printStackTrace();
            }
            throw new RuntimeException(e.getMessage());
        }
        
        close();
        return result;
    }
    
 
    // DB 자원해제
    private void close()
    {
        try {
            if ( pstmt != null ){ pstmt.close(); pstmt=null; }
            if ( conn != null ){ conn.close(); conn=null;    }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    } // end close()
}
 
cs



■ BoardListForm.jsp




글 목록 화면에서는 답글일 경우 공백과 제목 앞에 RE : 를 추가하도록 하였다. 공백의 수는 답글의 깊이만큼 추가한다.


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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>        
<html>
<head>
    <title>전체 게시글</title>
    
    <style type="text/css">
        #wrap {
            width: 800px;
            margin: 0 auto 0 auto;
        }
        #topForm{
            text-align :right;
        }
        #board, #pageForm, #searchForm{
            text-align :center;
        }
        
        #bList{
            text-align :center;
        }
    </style>
    
    <script type="text/javascript">
        function writeForm(){
            location.href="BoardWriteForm.bo";
        }
    </script>
    
</head>
<body>    
 
<div id="wrap">
 
    <!-- 글목록 위 부분-->
    <br>
    <div id="topForm">
        <c:if test="${sessionScope.sessionID!=null}">
            <input type="button" value="글쓰기" onclick="writeForm()">
        </c:if>    
    </div>
    
    <!-- 게시글 목록 부분 -->
    <br>
    <div id="board">
        <table id="bList" width="800" border="3" bordercolor="lightgray">
            <tr heigh="30">
                <td>글번호</td>
                <td>제목</td>
                <td>작성자</td>
                <td>작성일</td>
                <td>조회수</td>
            </tr>
        <c:forEach var="board" items="${requestScope.list}">
            <tr>
                <td>${board.board_num}</td>
                <td align="left">
                    <c:if test="${board.board_re_lev > 0}">
                        <c:forEach begin="1" end="${board.board_re_lev}">
                            &nbsp;&nbsp; <!-- 답변글일경우 글 제목 앞에 공백을 준다. -->
                        </c:forEach>
                        RE : 
                    </c:if>
                    <a href="BoardDetailAction.bo?num=${board.board_num}&pageNum=${spage}">
                    ${board.board_subject}
                    </a>
                </td>
                <td>
                    <a href="#">
                    ${board.board_id}
                    </a>
                </td>
                <td>${board.board_date}</td>
                <td>${board.board_count}</td>
            </tr>
        </c:forEach>
        </table>
    </div>
    
    <!-- 페이지 넘버 부분 -->
    <br>
    <div id="pageForm">
        <c:if test="${startPage != 1}">
            <a href='BoardListAction.bo?page=${startPage-1}'>[ 이전 ]</a>
        </c:if>
        
        <c:forEach var="pageNum" begin="${startPage}" end="${endPage}">
            <c:if test="${pageNum == spage}">
                ${pageNum}&nbsp;
            </c:if>
            <c:if test="${pageNum != spage}">
                <a href='BoardListAction.bo?page=${pageNum}'>${pageNum}&nbsp;</a>
            </c:if>
        </c:forEach>
        
        <c:if test="${endPage != maxPage }">
            <a href='BoardListAction.bo?page=${endPage+1 }'>[다음]</a>
        </c:if>
    </div>
    
    <!--  검색 부분 -->
    <br>
    <div id="searchForm">
        <form>
            <select name="opt">
                <option value="0">제목</option>
                <option value="1">내용</option>
                <option value="2">제목+내용</option>
                <option value="3">글쓴이</option>
            </select>
            <input type="text" size="20" name="condition"/>&nbsp;
            <input type="submit" value="검색"/>
        </form>    
    </div>
</div>    
 
</body>
</html>
cs



3. 실행 결과









4. 소스코드 다운로드 (war 파일)


JSP_DEV.war



RSS구독 링크추가 트위터 이메일 구독