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

Back-End/JSP 2019. 5. 25. 22:14
728x90
반응형

게시글 내용 확인 구현



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



728x90
반응형
: