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




: