티스토리 뷰

게시판정복/JSP게시판

2. 게시판 목록

/daydreamer 2017. 3. 28. 20:00

JSP만 사용해서 만드는 게시판

  • MariaDB 사용
  • 기본적인 CRUD
    Create/Read/Update/Delete




게시판 목록 생성

게시판을 만들어보댜! 먼저 글 목록의 틀을 잡아야 한다고 생각하였다.
글 생성을 목록에서부터 시작하게되고, 생성 후 다시 목록으로 돌아와야 하며,
상세를 보려거든 목록에서 클릭되어야 하고, 수정/삭제 후 다시 목록으로 와야하기 때문이다.

게시판 목록을 생각해보자.
등록한 글들이 차례로 쌓여야 하고 글번호/작성자/글제목/등록시간 이 있어야 한다.
글 내용은 상세 페이지로 들어갔을 때 보여줘도 되니까.

그렇다면 DB에 있는 데이터들이 select 되어 목록 화면에 table형태로 뿌려지면 될것이다.


1.

먼저 html 소스를 보면 글작성 할 수 있는 버튼을 만들었다. 
클릭 시 글쓰기 화면으로 이동할 수 있게 onclick 이벤트로 링크를 걸어주었다.
button 에 링크를 걸때 onclick을 사용한다. a태그 ㄴㄴ

그리고 table 태그를 사용하여 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
<body>
    <div>
        <h1>게시판</h1>
    </div>
    <div>
        <button type="button" title="글쓰기" onclick="location.href='create.jsp'">글쓰기</button>
        <!-- button에 링크 걸때는 onclick을 사용한다 (a태그 안댐) -->
    </div>
    <div>
        <table>
            <colgroup>
                <col width="10%" />
                <col width="30%" />
                <col width="20%" />
                <col width="30%" />
            </colgroup>
            <tr>
                <th>No</th>
                <th>제목</th>
                <th>작성자</th>
                <th>작성시간</th>
            </tr>        
        </table>        
    </div>
</body>
cs



2.

그리고 이제 DB연결을 해준다.
저번 포스팅에서 DB연결 해준것처럼 JSP페이지에서 DB의 데이터를 가져오려면 jdbc를 사용하여 DB를 연결해주어야 한다.

sql을 사용하니까 java.sql 을 import 해준다.
java 코드를 사용하므로 <% %> 으로 감싸주며 이 코드는 맨 상단에 위치한다.

DB에 연결을 해서 쿼리문을 보낸다.
나는 글번호를 입력하기 위해서 전체 글 개수를 가져와야하고, 전체 데이터를 가져와야 해서
2개의 쿼리가 필요하다.

countrs에 board 테이블의 전체 갯수를 가져오고 select count(*) from board
rs에 board테이블의 전체 데이터를 내림차순으로 가져온다.

countrs.next()를 이용하여 데이터를 한줄씩 읽어들인다. countrs.next()를 실행하면 받아온데이터의 첫줄 위치로 이동하게 된다.
countrs.getInt(1)은 select 문에서 첫번째 항목을 int 형으로 가져오는 것인데 갯수를 가져오는 쿼리를 날렸으니 int형이 맞다.
그렇다면 데이터의 총 개수를 가져왔을 테니, 그것을 count 에 집어 넣는다.

이제 가져온 데이터를 이용하여 목록에 뿌려보자!


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
<%@ page import="java.sql.*" %>      
<% 
    //DB연결
    Connection conn = null;
    Statement stmt = null;
    int count=0;
    
    
    try{
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/haeun?useUnicode=true&characterEncoding=utf-8","id","pw");
        //db insert시 한글 깨져서 db명 뒤에 ?useUnicode=true&characterEncoding=utf-8 붙여준다.
        if(conn == null)
            throw new Exception("데이터베이스에 연결할 수 없습니다.");
        stmt = conn.createStatement();
 
        ResultSet countrs = stmt.executeQuery("select count(*) from board;");
        //ResultSet은 select 문을 사용하여 얻어온 레코드 값들을 테이블의 형태로 갖게 되는 객체 
        
        if(countrs.next()){ //이곳의 의미는?
            count = countrs.getInt(1);
        }
        
        ResultSet rs = stmt.executeQuery("select * from board order by idx desc;");
                
        
%>
cs


3.

count가 데이터의 총 개수이므로 0일땐 게시글이 없으니, 데이터가 없다는 글을 보여준다.
데이터가 있을 때는 while문을 돌면서 rs의 첫줄부터 끝날 때 까지 데이터를 뿌려준다.

첫번째 줄에는 가장 최근에 등록한 글이 오게 되므로 count는 한 데이터가 지날수록 -1씩 감소해야 한다.
그래서 마지막에 count를 -1 해준 것이다.

글 제목/작성자/시간은 rs.의 getString()을 사용하여 게시판에 뿌려준다.

td에 onClick 을 준 것은 글 목록에서 글을 선택했을 때 상세페이지로 이동하기 위해서다.
이부분은 javascript를 사용하였는데 클릭 시 goToDetail함수로 이동하게 된다.
rs에서 가져온 idx를 주면 상세페이지로 넘어갈 때 PK 인 idx를 가지고 넘어가므로 그 idx를 가지고 있는 상세글 페이지로 이동한다.

1
2
3
4
5
<script type="text/javascript">
    function goToDetail(idx){
        location.href="detail.jsp?idx="+idx; //페이지 이동
    }
</script>
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<%
        if(count==0){
            out.print("<tr><td colspan='4'>데이터가 없습니다.</td></tr>");
        }else{
             while(rs.next()){
                out.print("<tr>"); //td에 onclick 주기 
//                 out.print("<td><a href='detail.jsp?idx=" + rs.getString("idx") +"'>"+ rs.getString("idx") + "</a></td>");
                out.print("<td onClick='goToDetail("+rs.getString("idx")+")'>"+ count + "</td>");
                out.print("<td onClick='goToDetail("+rs.getString("idx")+")'>" + rs.getString("title"+ "</td>");
                out.print("<td onClick='goToDetail("+rs.getString("idx")+")'>" + rs.getString("name"+ "</td>");
                out.print("<td onClick='goToDetail("+rs.getString("idx")+")'>" + rs.getString("time"+ "</td>");
                out.print("</tr>");
                
                count=count-1;
            }             
        }
 
%>    
cs


4.

마지막으로 DB 연결을 끊는다.

exception이 발생했다면 catch 문에서 DB에 문제가 있다고 나올것이지만. 
잘 연결되어 모든 작업이 끝났다면 conn.close()를 통해 DB 연결을 끊어줄 것이다.


1
2
3
4
5
6
7
8
<%
        conn.close();
    }catch(Exception e){
        out.println("데이터베이스에 문제가 있습니다.");
        out.println(e.getMessage());
        e.getStackTrace();
    }
%>    
cs



전체 소스 

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=utf-8"
    pageEncoding="utf-8"%>
<%@ page import="java.sql.*" %>      
<% 
    //DB연결
    Connection conn = null;
    Statement stmt = null;
    int count=0;
    
    
    try{
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/haeun?useUnicode=true&characterEncoding=utf-8","khe","1231");
        //db insert시 한글 깨져서 db명 뒤에 ?useUnicode=true&characterEncoding=utf-8 붙여준다.
        if(conn == null)
            throw new Exception("데이터베이스에 연결할 수 없습니다.");
        stmt = conn.createStatement();
 
        ResultSet countrs = stmt.executeQuery("select count(*) from board;");
        //ResultSet은 select 문을 사용하여 얻어온 레코드 값들을 테이블의 형태로 갖게 되는 객체 
        
        if(countrs.next()){ //이곳의 의미는?
            count = countrs.getInt(1);
        }
        
        ResultSet rs = stmt.executeQuery("select * from board order by idx desc;");
                
        
%>
<!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=utf-8">
<link rel="stylesheet" type="text/css" href="/JSP_Board/css/layout.css"/>
<title>게시판</title>
<script type="text/javascript">
    function goToDetail(idx){
        location.href="detail.jsp?idx="+idx; //페이지 이동
    }
</script>
</head>
<body>
 
    <div>
        <h1>게시판</h1>
    </div>
    
    <div>
        <button type="button" title="글쓰기" onclick="location.href='create.jsp'">글쓰기</button>
        <!-- button에 링크 걸때는 onclick을 사용한다 (a태그 안댐) -->
    </div>
    
    <div>
        <table>
            <colgroup>
                <col width="10%" />
                <col width="30%" />
                <col width="20%" />
                <col width="30%" />
            </colgroup>
            <tr>
                <th>No</th>
                <th>제목</th>
                <th>작성자</th>
                <th>작성시간</th>
            </tr>
<%
        if(count==0){
            out.print("<tr><td colspan='4'>데이터가 없습니다.</td></tr>");
        }else{
             while(rs.next()){
                out.print("<tr>"); //td에 onclick 주기 
//                 out.print("<td><a href='detail.jsp?idx=" + rs.getString("idx") +"'>"+ rs.getString("idx") + "</a></td>");
                out.print("<td onClick='goToDetail("+rs.getString("idx")+")'>"+ count + "</td>");
                out.print("<td onClick='goToDetail("+rs.getString("idx")+")'>" + rs.getString("title"+ "</td>");
                out.print("<td onClick='goToDetail("+rs.getString("idx")+")'>" + rs.getString("name"+ "</td>");
                out.print("<td onClick='goToDetail("+rs.getString("idx")+")'>" + rs.getString("time"+ "</td>");
                out.print("</tr>");
                
                count=count-1;
            }             
        }
 
%>            
        </table>
        
    </div>
<%
        conn.close();
    }catch(Exception e){
        out.println("데이터베이스에 문제가 있습니다.");
        out.println(e.getMessage());
        e.getStackTrace();
    }
%>    
</body>
</html>
cs


'게시판정복 > JSP게시판' 카테고리의 다른 글

6. 게시판 글 삭제  (0) 2017.04.07
5. 게시판 글 수정  (0) 2017.04.07
4. 게시판 상세보기  (0) 2017.04.04
3. 게시판 글 생성  (0) 2017.03.28
1. 페이지설계/ TABLE설계/ JDBC/ 이클립스DB연결  (1) 2017.02.21
댓글