-
게시판 하단에 페이지 표시하기
-
한 페이지당 몇 개의 게시글을 표시할 것인가?
-
int pageSize=5 (5개의 게시글)
-
글이 하나만 있더라도 페이지는 1로 표시된다.
-
String pageNum (String으로 pageNum을 reqest 받아옴)
-
int currentPage (현재 페이지. String pageNum을 int형으로 변환)
-
10개의 게시글이 있다고 가정했을때 1페이지에는 6~10번째, 2페이지에는 1~5번째 게시글이 표시된다.
-
페이지당 표시되는 게시글의 첫번째를 startRow, 마지막번째를 endRow라고 한다.
-
startRow=(currentPage-1)*pageSize+1; (현재 페이지가 1이라면 startRow는 1)
-
endRow=currentPage*pageSize; (현재 페이지가 1이라면 endRow는 5)
-
페이지가 없었던 기존: 게시글 전체를 arr에 담아 화면에 표시했다.
-
페이지가 있는 지금: arr에 startRow와 endRow인자를 사용하여 표시
-
검색이 아닌 전체보기: arr=dao.boardList(startRow, endRow)
-
검색 전체보기: arr=dao.boardList(field, word, startRow, endRow)
-
하단에 페이지 숫자를 몇 개씩 표시할 것인가?
-
int pageBolck=3 (123 456 처럼 3개씩)
-
게시글 양에 따라 필요한 페이지의 수는?
-
int pageCount=count/pageSize+(count%pageSize==0? 0:1)
-
11=53/5+(53%5==0)
-
시작페이지
-
int startPage=(int)((currentPage-1)/pageBlock)*pageBlock+1;
-
마지막페이지
-
int endPage=startPage+pageBlock-1;
-
만약 마지막페이지가 필요한 페이지보다 크다면: endPage=pageCount;
-
'이전' 이란 표시는 언제 생겨나는가?
-
시작페이지가 필요한 페이지보다 클때
-
startPage>pageBlock
-
페이지 표시
-
for문을 돌려서 starPage에서 endPage까지 1씩 커지도록함
-
'다음' 이란 표시는 언제 생겨나는가?
-
마지막페이지가 필요한 페이지보다 작을때
-
endPage<pageCount
-
DB에서 boardList로 값 가져오기
-
최신글부터 표시되어야 함
-
select * from board order by num desc;
-
그러나 num은 일정하지 않은 변수(게시글 삭제를 하면). 따라서 rownum이라는 키워드를 이용
-
select rownum rn, aa.* from(select * from board order by num desc) aa;
-
board 테이블을 aa라는 테이블로 명명하고
-
rownum을 rn이라는 이름의 컬럼으로, aa와 함께 출력
-
페이지당 필요한 게시글 수 만큼 뽑아와야 함.
-
select * from (
-
select rownum rn, aa.* from(
-
select * from board order by num desc) aa
-
) where rn <=? and rn >=?;
-
?에는 endrow와 startrow가 들어감
-
검색한 게시글을 불러올 경우
-
select * from (
-
select rownum rn, aa.* from(
-
select * from board where filed like '%word%' order by num desc) aa
-
) where rn <=? and rn >=?;
-
?에는 endrow와 startrow가 들어감
-
답글쓰기
-
새 글을 쓸때 writeForm: 글 번호가 없다.
-
답글을 쓸때 writeForm: 글 번호가 있다.
-
ref: 그룹 (새 글에는 새 그룹). 게시글 순서
-
re_step: 답글 순서
-
re_level: 답글의 답글 순서
-
list.jsp: 페이지 표시하도록 수정
<%@page import="com.board.BoardVO"%>
<%@page import="com.board.BoardDAO"%>
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<style>
div.divCss{
text-align: right;
background-color: darkgray;
padding-right: 20px;
}
a:hover { text-decoration: none; }
a:link {text-decoration: none; }
a:visited {text-decoration: none; }
</style>
</head>
<%
request.setCharacterEncoding("utf-8");
String pageNum=request.getParameter("pageNum");
if(pageNum==null){
pageNum="1";
}
int currentPage=Integer.parseInt(pageNum);
BoardDAO dao=BoardDAO.getInstance();
int pageSize=5; //한페이지당 5개씩
int startRow=(currentPage-1)*pageSize+1;
int endRow=currentPage*pageSize;
String field="", word="";
ArrayList<BoardVO> arr=null;
int count=0;
if(request.getParameter("word")!=null&&!request.getParameter("word").equals("")){ //검색일때
field=request.getParameter("field");
word=request.getParameter("word");
arr=dao.boardList(field,word,startRow,endRow);
count=dao.boardCount(field,word);
}else{ //검색아닐때
arr=dao.boardList(startRow,endRow);
count=dao.boardCount();
}
String userid=(String)session.getAttribute("userid");
%>
<body>
<div align="right">
<%
if(userid!=null){
%>
<%=userid %>님 반갑습니다.
<a href="../member/logout.jsp">로그아웃</a>
<%
}
%>
<br>전체 게시글 수: <span id="cntSpan"><%=count %></span><br>
<a href="writeForm.jsp">글쓰기</a>
</div>
<table class="table table-striped">
<thead>
<tr>
<th scope="col">번호</th>
<th>제목</th>
<th>작성자</th>
<th>작성일</th>
<th>조회수</th>
<th>IP주소</th>
</tr>
</thead>
<tbody>
<%
for(BoardVO vo: arr){
%>
<tr>
<th scope="row"><%=vo.getNum()%></th>
<td><a href="boardView.jsp?num=<%=vo.getNum()%>"><%=vo.getSubject() %></a></td>
<td><%=vo.getWriter() %></td>
<td><%=vo.getReg_date()%></td>
<td><%=vo.getReadcount() %></td>
<td><%=vo.getIp() %></td>
</tr>
<%
}
%>
</tbody>
</table>
<br><br>
<form action="list.jsp" name="search" method="get">
<table align=center>
<tr>
<td>
<select name="field" size=1>
<option value="subject">제목
<option value="writer">작성자
</select>
<input type="text" size=16 name="word">
<input type="submit" value="찾기">
</td>
</tr>
</table>
</form>
<div align="center">
<%
if(count>0){ // 11= 53/5 + (53%5==0) 53개 게시물을 한페이지당 5개씩 보여준다면 11개의 페이지가 필요
int pageCount=count/pageSize+(count%pageSize==0? 0:1);
int pageBlock=3; //123 456 등 3페이지씩 표시
int startPage=(int)((currentPage-1)/pageBlock)*pageBlock+1; //시작페이지
int endPage=startPage+pageBlock-1; //마지막 페이지 12
if(endPage>pageCount){
endPage=pageCount; //endPage=11;
}
if(startPage>pageBlock){ //이전
%>
<a href="list.jsp?pageNum=<%=startPage-pageBlock%>&field=<%=field%>&word=<%=word %>">[이전]</a>
<%
}
for(int i=startPage;i<=endPage;i++){ //for
%>
<a href="list.jsp?pageNum=<%=i%>&field=<%=field%>&word=<%=word %>"><%=i%></a>
<%
}
if(endPage<pageCount){ //다음
%>
<a href="list.jsp?pageNum=<%=startPage+pageBlock%>&field=<%=field%>&word=<%=word %>">[다음]</a>
<%
}
}
%>
</div>
</body>
</html>
-
writeForm.jsp: 답글과 새글의 차이점 만들어주기
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<%
request.setCharacterEncoding("utf-8");
int num=0, ref=1, re_step=0, re_level=0; //새글
if(request.getParameter("num")!=null){ //답글
num=Integer.parseInt(request.getParameter("num"));
ref=Integer.parseInt(request.getParameter("ref"));
re_step=Integer.parseInt(request.getParameter("re_step"));
re_level=Integer.parseInt(request.getParameter("re_level"));
}
%>
<body>
<form action="writePro.jsp" method="post">
<input type="hidden" name="num" value=<%=num %>>
<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 %>>
<table border=1>
<tr>
<td>이름</td>
<td><input type="text" name="writer"></td>
</tr>
<tr>
<td>제목</td>
<td>
<%
if(request.getParameter("num")!=null){ //답글
%>
<input type="text" name="subject" value="[답글]">
<%
}else{ //새글
%>
<input type="text" name="subject">
<%
}
%>
</td>
</tr>
<tr>
<td>이메일</td>
<td><input type="text" name="email"></td>
</tr>
<tr>
<td>내용</td>
<td><textarea cols="50" rows="20" name="content"></textarea></td>
</tr>
<tr>
<td>비밀번호</td>
<td><input type="password" name="passwd"></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="글쓰기">
<input type="reset" value="다시 작성">
<input type="button" value="목록보기" onclick="location.href='list.jsp'">
</td>
</tr>
</table>
</form>
</body>
</html>
-
boardView.jsp: ref, re_step, re_level 값을 불러오고 각종 버튼에 jsp연결 시키기, 댓글쓰기 란 만들기 (제이쿼리 주소 붙여넣고 스크립트 안에 ajax으로 commentInser.jsp 연결)
<%@page import="com.board.BoardVO"%>
<%@page import="com.board.BoardDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<%
request.setCharacterEncoding("utf-8");
int num=Integer.parseInt(request.getParameter("num"));
BoardDAO dao=BoardDAO.getInstance();
BoardVO board=dao.boardView(num);
int ref=board.getRef();
int re_step=board.getRe_step();
int re_level=board.getRe_level();
String userid=(String)session.getAttribute("userid");
%>
</head>
<script>
function del(){
if(confirm("정말 삭제할까요?")){
location.href="deletePro.jsp?num=<%=num%>";
}
}
</script>
<body>
<h2>글 내용 보기</h2>
<table border=1 width=500>
<input type="hidden" name="num" id="num" value="<%=num%>">
<tr>
<td>글번호</td>
<td><%=board.getNum() %></td>
<td>조회수</td>
<td><%=board.getReadcount() %></td>
</tr>
<tr>
<td>작성자</td>
<td><%=board.getWriter() %></td>
<td>작성일</td>
<td><%=board.getReg_date() %></td>
</tr>
<tr>
<td>글제목</td>
<td colspan="3"><%=board.getSubject() %></td>
</tr>
<tr>
<td>글내용</td>
<td colspan="3"><%=board.getContent() %></td>
</tr>
<tr>
<td colspan="4">
<input type="button" value="글수정" onclick="location.href='updateForm.jsp?num=<%=num%>'">
<input type="button" value="글삭제" onclick="del()">
<input type="button" value="답글쓰기" onclick="location.href='writeForm.jsp?num=<%=num%>&ref=<%=ref%>&re_step=<%=re_step%>&re_level=<%=re_level%>'">
<input type="button" value="글목록" onclick="location.href='list.jsp'">
</td>
</tr>
</table>
<br><br><br><br>
<div align="center">
<textarea rows="5" cols="50" id="msg"></textarea>
<input type="button" value="댓글쓰기" id="commentBtn">
</div>
<div id="area"></div>
<script>
var init=function(){
$.getJSON("commentList.jsp?num="+$("#num").val(), function(data){
var htmlStr="<table>";
$.each(data, function(key,val){
htmlStr+="<tr>";
htmlStr+="<td>"+val.msg+"</td>";
htmlStr+="<th>"+"작성자: "+val.userid+"</th>";
htmlStr+="<td>"+val.reg_date+"</td>";
if('<%=userid%>'==val.userid){
htmlStr+="<td onclick='del()'><input type='button' value='삭제'></td>";
}
htmlStr+="</tr>";
});
htmlStr+="</table>";
$("#area").html(htmlStr);
}) //getJSON
}//init
function del(){
if(confirm("정말 삭제할까요?")){
}
}
$("#commentBtn").on("click",function(){
$.ajax({
type:"post",
url :"commentInsert.jsp",
data: {"msg":$("#msg").val(), "num":$("#num").val()},
success: function(resp){
if(resp.trim()=="1"){
alert("로그인 후 댓글쓰기");
//location.href="../member/loginForm.jsp";
location.href="/JSP_Project/member/loginForm.jsp";
}else{
//화면에 리스트 뿌리기
init();
}
},
error: function(e){
alert("error:"+e);
}
});
});
init();
</script>
</body>
</html>
-
updateForm.jsp: 답글 표시, 목록보기에 list.jsp 연결
<%@page import="com.board.BoardVO"%>
<%@page import="com.board.BoardDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<%
request.setCharacterEncoding("utf-8");
int num=Integer.parseInt(request.getParameter("num"));
BoardDAO dao=BoardDAO.getInstance();
BoardVO board=dao.boardView(num);
%>
</head>
<body>
<h1>글 수정하기</h1>
<form action="updatePro.jsp" method="post">
<input type="hidden" name="num" value="<%=num%>">
<table border=1>
<tr>
<td>이름</td>
<td><%=board.getWriter()%></td>
</tr>
<tr>
<td>제목</td>
<td><input type="text" name="subject" value="<%=board.getSubject()%>"></td>
</tr>
<tr>
<td>이메일</td>
<td><input type="text" name="email" value="<%=board.getEmail()%>"></td>
</tr>
<tr>
<td>내용</td>
<td><textarea cols="50" rows="20" name="content"><%=board.getContent()%></textarea></td>
</tr>
<tr>
<td>비밀번호</td>
<td><input type="password" name="passwd"></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="수정">
<input type="reset" value="다시 작성">
<input type="button" value="목록보기" onclick="location.href='list.jsp'">
</td>
</tr>
</table>
</form>
</body>
</html>
-
BoardDAO.java: 답글과 페이지에 따라 추가, 보기, 갱신 등 수정하기
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359package com.board;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.ArrayList;import javax.naming.Context;import javax.naming.InitialContext;import javax.sql.DataSource;public class BoardDAO {//디비셋팅private static BoardDAO instance=new BoardDAO();public static BoardDAO getInstance() {return instance;}private Connection getConnection() throws Exception{Context initCtx=new InitialContext();Context envCtx=(Context) initCtx.lookup("java:comp/env");DataSource ds=(DataSource) envCtx.lookup("jdbc/member");return ds.getConnection();}//추가public void boardInsert(BoardVO board) { //새글 답글 구분Connection con=null;PreparedStatement ps=null;ResultSet rs=null;//부모글int num=board.getNum();int ref=board.getRef(); //게시글 순서int re_step=board.getRe_step(); //답글 순서int re_level=board.getRe_level(); //답글의 답글 순서int number=0;String sql=null;try {con=getConnection();ps=con.prepareStatement("select max(num) from board");rs=ps.executeQuery();if(rs.next()) { //기존 데이터가 있을때 ref를 최대값 +1 로 결정number=rs.getInt(1)+1;}else { //기존 데이터가 없을때 ref를 1로 결정number=1;}if(num!=0) { //답글sql="update board set re_step=re_step+1 where ref=? and re_step>?";ps=con.prepareStatement(sql);ps.setInt(1, ref);ps.setInt(2, re_step);ps.executeUpdate();re_step=re_step+1;re_level=re_level+1;}else { //새글ref=number;re_step=0;re_level=0;}//num, writer, subject, email, content, passwd, ip, readcount, ref, re_step, re_levelsql="INSERT INTO BOARD(num,writer,subject,email,content,passwd,ip,readcount,ref,re_step,re_level)"+ "VALUES (board_seq.nextval,?,?,?,?,?,?,0,?,?,?)";ps=con.prepareStatement(sql);ps.setString(1, board.getWriter());ps.setString(2, board.getSubject());ps.setString(3, board.getEmail());ps.setString(4, board.getContent());ps.setString(5, board.getPasswd());ps.setString(6, board.getIp());ps.setInt(7, ref);ps.setInt(8, re_step);ps.setInt(9, re_level);ps.executeUpdate();} catch (Exception e) {e.printStackTrace();} finally {closeConnection(con,ps,rs);}}//전체보기public ArrayList<BoardVO> boardList(int startRow, int endRow){Connection con=null;PreparedStatement ps=null;ResultSet rs=null;ArrayList<BoardVO> arr=new ArrayList<BoardVO>();try {con=getConnection(); //게시글은 최신순. 답글은 오래된 순.String sql="select * from ("+ "select rownum rn, aa.* from ("+ "select * from board order by ref desc, re_step asc) aa "+ ") where rn <=? and rn >=?";ps=con.prepareStatement(sql);ps.setInt(1, endRow);ps.setInt(2, startRow);rs=ps.executeQuery();while(rs.next()) {BoardVO board=new BoardVO();board.setNum(rs.getInt("num"));board.setEmail(rs.getString("email"));board.setIp(rs.getString("ip"));board.setReadcount(rs.getInt("readcount"));board.setSubject(rs.getString("subject"));board.setWriter(rs.getString("writer"));board.setReg_date(rs.getString("reg_date"));arr.add(board);}} catch (Exception e) {e.printStackTrace();} finally {closeConnection(con, ps, rs);}return arr;}//검색 전체보기public ArrayList<BoardVO> boardList(String field, String word, int startRow, int endRow){Connection con=null;PreparedStatement ps=null;ResultSet rs=null;ArrayList<BoardVO> arr=new ArrayList<BoardVO>();try {con=getConnection();String sql="select * from ("+ "select rownum rn, aa.* from ("+ "select * from board where "+field+" like '%"+word+"%' order by ref desc, re_step asc) aa "+ ") where rn <=? and rn >=?";ps=con.prepareStatement(sql);ps.setInt(1, endRow);ps.setInt(2, startRow);rs=ps.executeQuery();while(rs.next()) {BoardVO board=new BoardVO();board.setNum(rs.getInt("num"));board.setEmail(rs.getString("email"));board.setIp(rs.getString("ip"));board.setReadcount(rs.getInt("readcount"));board.setSubject(rs.getString("subject"));board.setWriter(rs.getString("writer"));board.setReg_date(rs.getString("reg_date"));arr.add(board);}} catch (Exception e) {e.printStackTrace();} finally {closeConnection(con, ps, rs);}return arr;}//상세보기public BoardVO boardView(int num) {Connection con=null;Statement st=null;ResultSet rs=null;BoardVO board=null;try {con=getConnection();st=con.createStatement();st.executeUpdate("update board set readcount=readcount+1 where num="+num);String sql="select * from board where num="+num;st=con.createStatement();rs=st.executeQuery(sql);if(rs.next()) {board=new BoardVO();board.setNum(rs.getInt("num"));board.setContent(rs.getString("content"));board.setEmail(rs.getString("email"));board.setSubject(rs.getString("subject"));board.setIp(rs.getString("ip"));board.setPasswd(rs.getString("passwd"));board.setRe_level(rs.getInt("re_level"));board.setRe_step(rs.getInt("re_step"));board.setRef(rs.getInt("ref"));board.setReg_date(rs.getString("reg_date"));board.setReadcount(rs.getInt("readcount"));board.setWriter(rs.getString("writer"));}}catch (Exception e) {e.printStackTrace();}finally {closeConnection(con, st, rs);}return board;}//수정public int boardUpdate(BoardVO board) {Connection con=null;PreparedStatement ps=null;ResultSet rs=null;int flag=0;String sql="";try {con=getConnection();sql="select passwd from board where num="+board.getNum();ps=con.prepareStatement(sql); //passwd 검색rs=ps.executeQuery();if(rs.next()) {if(rs.getString("passwd").equals(board.getPasswd())) { //비번 일치sql="UPDATE BOARD SET subject=?, email=?, content=?, reg_date=sysdate where num=?";ps=con.prepareStatement(sql);ps.setString(1, board.getSubject());ps.setString(2, board.getEmail());ps.setString(3, board.getContent());ps.setInt(4, board.getNum());flag=ps.executeUpdate(); //업데이트 된 수를 flag에 담는다.}}}catch (Exception e) {e.printStackTrace();}finally {closeConnection(con, ps);}return flag;}//삭제public int boardDelete(int num) {int flag=0;Connection con=null;Statement st=null;try {con=getConnection();String sql="DELETE FROM board WHERE num="+num;st=con.createStatement();flag=st.executeUpdate(sql);} catch (Exception e) {e.printStackTrace();} finally {closeConnection(con, st, null);}return flag;}//개수public int boardCount() {Connection con=null;Statement st=null;ResultSet rs=null;int count=0;try {con=getConnection();st=con.createStatement();String sql="select count(*) from board";rs=st.executeQuery(sql);if(rs.next()) {count=rs.getInt(1);}} catch (Exception e) {e.printStackTrace();} finally {closeConnection(con, st, rs);}return count;}//검색 개수public int boardCount(String field, String word) {Connection con=null;Statement st=null;ResultSet rs=null;int count=0;try {con=getConnection();st=con.createStatement();String sql="select count(*) from board where "+field+" like '%"+word+"%'";rs=st.executeQuery(sql);if(rs.next()) {count=rs.getInt(1);}} catch (Exception e) {e.printStackTrace();} finally {closeConnection(con, st, rs);}return count;}//comment//commentInsertpublic void commentInsert(CommentVO cvo) {Connection con=null;PreparedStatement ps=null;try {con=getConnection();String sql="INSERT INTO commentboard(cnum, userid, msg, bnum)"+ "VALUES(comment_seq.nextval,?,?,?)";ps=con.prepareStatement(sql);ps.setString(1, cvo.getUserid());ps.setString(2, cvo.getMsg());ps.setInt(3, cvo.getBnum());ps.executeUpdate();} catch (Exception e) {e.printStackTrace();} finally {closeConnection(con, ps);}}//commentListpublic ArrayList<CommentVO> commentList(int num){Connection con=null;Statement st=null;ResultSet rs=null;ArrayList<CommentVO> arr=new ArrayList<CommentVO>();try {con=getConnection();String sql="SELECT * FROM COMMENTBOARD where bnum="+num+" ORDER BY cnum DESC";st=con.createStatement();rs=st.executeQuery(sql);while(rs.next()) {CommentVO comment=new CommentVO();comment.setBnum(rs.getInt("bnum"));comment.setCnum(rs.getInt("cnum"));comment.setMsg(rs.getString("msg"));comment.setReg_date(rs.getString("reg_date"));comment.setUserid(rs.getString("userid"));arr.add(comment);}} catch (Exception e) {e.printStackTrace();} finally {closeConnection(con, st, rs);}return arr;}//닫기 closeConnectionprivate void closeConnection(Connection con, PreparedStatement ps) {try {if(ps!=null) ps.close();if(con!=null) con.close();} catch (SQLException e) {e.printStackTrace();}}private void closeConnection(Connection con, Statement st, ResultSet rs) {try {if(st!=null) st.close();if(con!=null) con.close();if(rs!=null) rs.close();} catch (SQLException e) {e.printStackTrace();}}}cs
-
commentboard 이름의 테이블을 생성하여 댓글 DB만들기. 댓글번호 cnum을 기본키로 하고 board테이블의 num을 bnum이름으로 외래키로 참조한다.
cnum으로 쓸 시퀀스 생성
-
CommentVO.java: 댓글 자바빈즈
package com.board;
public class CommentVO {
private int cnum;
private String userid;
private String reg_date;
private String msg;
private int bnum;
public int getCnum() {
return cnum;
}
public void setCnum(int cnum) {
this.cnum = cnum;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getReg_date() {
return reg_date;
}
public void setReg_date(String reg_date) {
this.reg_date = reg_date;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getBnum() {
return bnum;
}
public void setBnum(int bnum) {
this.bnum = bnum;
}
}
-
commentInsert.jsp: 댓글 입력 로직
<%@page import="com.board.BoardDAO"%>
<%@page import="com.board.CommentVO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
request.setCharacterEncoding("utf-8");
String msg=request.getParameter("msg");
int num=Integer.parseInt(request.getParameter("num"));
String userid=(String)session.getAttribute("userid");
if(userid==null){ //로그인 안됨
out.println("1");
}else{ //로그인
CommentVO comment=new CommentVO();
comment.setUserid(userid);
comment.setMsg(msg);
comment.setBnum(num);
BoardDAO dao=BoardDAO.getInstance();
dao.commentInsert(comment);
}
%>
-
commentList.jsp: 댓글 목록
<%@page import="org.json.simple.JSONObject"%>
<%@page import="org.json.simple.JSONArray"%>
<%@page import="com.board.CommentVO"%>
<%@page import="java.util.ArrayList"%>
<%@page import="com.board.BoardDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
request.setCharacterEncoding("utf-8");
int num=Integer.parseInt(request.getParameter("num"));
BoardDAO dao=BoardDAO.getInstance();
ArrayList<CommentVO>arr=dao.commentList(num);
JSONArray jarr=new JSONArray();
for(CommentVO cb:arr){
JSONObject obj=new JSONObject();
obj.put("bnum",cb.getBnum());
obj.put("cnum",cb.getCnum());
obj.put("msg",cb.getMsg());
obj.put("userid",cb.getUserid());
obj.put("reg_date",cb.getReg_date());
jarr.add(obj);
}
out.println(jarr.toString());
%>