본문 바로가기
[ View ]/JSP

[ JSP ] 게시판 만들기 3 - 댓글 기능 추가

by 환이s 2023. 3. 30.

이전 포스팅에 이어서 오늘은 댓글 기능을 추가해 보겠습니다.

 

 

게시판 기능/ 파일 구조

 

< 기능 >

1 ) CRUD(글쓰기, 목록/상세, 수정, 삭제)

2 ) 검색 기능

3 ) 페이지 나누기

4) 파일 업로드, 다운로드

5 ) 댓글 달기

6 ) 답변 달기

 

< 파일 구조 >

Contoller

BoardController.java

Model

Pager.java Constants.java (상수값들)
BoardDTO.java
BoardCommentDTO.java(댓글 관련)
BoardDAO.java
board.xml

View

index.jsp : 시작 페이지
list.jsp : 게시판 목록
write.jsp : 글쓰기
view.jsp : 상세 화면
comment_list.jsp : 댓글 목록
edit.jsp : 수정, 삭제 기능
reply.jsp : 답변 달기
search.jsp : 검색 페이지

SQL Table 생성

 

댓글 목록 데이터를 담아두기 위해 추가로 댓글 테이블을 생성합니다. 

 

--2) board_comment(댓글 테이블) 생성
-- references 테이블(컬럼) Foreign Key(외래키) 
create table board_comment (
comment_num number not null primary key, --댓글 일련번호
board_num number not null references board(num), --Foreign Key 
writer varchar2(50) not null,
content clob not null, --큰내용을 처리할 수 있게 clob을 써본다.
reg_date date default sysdate
);

 

다음으로 댓글 데이터 객체를 생성하기 위해 DTO를 생성합니다.


BoardCommentDTO

 

package board.dto;

import java.util.Date;

public class BoardCommentDTO {
	private int comment_num;
	private int board_num;
	private String writer;
	private String content;
	private Date reg_date;
	//getter,setter,toString
	public int getComment_num() {
		return comment_num;
	}
	public void setComment_num(int comment_num) {
		this.comment_num = comment_num;
	}
	public int getBoard_num() {
		return board_num;
	}
	public void setBoard_num(int board_num) {
		this.board_num = board_num;
	}
	public String getWriter() {
		return writer;
	}
	public void setWriter(String writer) {
		this.writer = writer;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public Date getReg_date() {
		return reg_date;
	}
	public void setReg_date(Date reg_date) {
		this.reg_date = reg_date;
	}
	@Override
	public String toString() {
		return "BoardCommentDTO [comment_num=" + comment_num + ", board_num=" + board_num + ", writer=" + writer
				+ ", content=" + content + ", reg_date=" + reg_date + "]";
	}
}

 


view.jsp

 

이전 포스팅에서 수정/삭제, 답변 버튼 및 text 폼을 만들었습니다.

 

<body>
<h2>상세 화면</h2>
<form name="form1" method="post">
<table border="1" style="width: 100%;">
 <tr>
  <td>날짜</td>
  <td>${dto.reg_date}</td>
  <td>조회수</td>
  <td>${dto.readcount}</td>
 </tr>
 <tr>
  <td>이름</td>
  <td colspan="3">${dto.writer}</td>
 </tr>
 <tr>
  <td>제목</td>
  <td colspan="3">${dto.subject}</td>
 </tr>
 <tr>
  <td>본문</td>
  <td colspan="3">${dto.content}</td>
 </tr>
 <tr>
  <td>비밀번호</td>
  <td colspan="3">
   <input type="password" name="passwd" id="passwd">
   <c:if test="${param.message == 'error'}">
    <span style="color: red;">비밀번호가 일치하지 않습니다.</span>
   </c:if>
  </td>
 </tr>
 <tr>
  <td>첨부파일</td>
  <td colspan="3">
   <c:if test="${dto.filesize > 0}">${dto.filename}(${dto.filesize} bytes )
    <a href="${path}/board_servlet/download.do?num=${dto.num}">[다운로드]</a>
   </c:if>
  </td>
 </tr>
 <tr>
  <td colspan="4" align="center">
   <input type="hidden" name="num" value="${dto.num}">
   <input type="button" value="수정/삭제" id="btnEdit">
   <input type="button" value="답변" id="btnReply">
   <input type="button" value="목록" id="btnList">
  </td>
 </tr>
</table>
</form>
<!-- 댓글 쓰기 폼 -->
<table border="1" style="width: 100%;">
 <tr>
  <td><input id="writer" placeholder="이름"></td>
  <td rowspan="2">
   <button id="btnSave" type="button">확인</button>
  </td>
 </tr>
 <tr>
  <td><textarea rows="5" cols="80" placeholder="내용을 입력하세요" id="content"></textarea></td>
 </tr>
</table>

<!-- 댓글 목록을 출력할 영역 -->
<div id="commentList"></div>

</body>
</html>

 

다음으로 각 버튼 클릭 시 이벤트 발생할 수 있게 자바 스크립트에서 Controller로 요청을 보냅니다.

 

 

< script code >

$(function() {
	comment_list();
	$("#btnSave").click(function() { /* 확인 */
		comment_add();
	});
	$("#btnList").click(function() { /* 목록 */
		location.href="${path}/board_servlet/list.do";
	});
	$("#btnReply").click(function() { /* 답변 */
		document.form1.action="${path}/board_servlet/reply.do";
		document.form1.submit();
	});
	$("#btnEdit").click(function() { /* 수정/삭제 */
		document.form1.action="${path}/board_servlet/pass_check.do";
		document.form1.submit();
	});
});
function comment_add() { /* 답글 쓰기 구현 */
	var param="board_num=${dto.num}&writer="+$("#writer").val()
	+"&content="+$("#content").val();
	$.ajax({
		type: "post",
		url: "${path}/board_servlet/comment_add.do",
		data: param,
		success: function() {
			$("#writer").val("");
			$("#content").val("");
			comment_list();
		}
	});
}
function comment_list() { /* 댓글 목록 출력 */
	$.ajax({
		type: "post",
		url: "${path}/board_servlet/commentList.do",
		data: "num=${dto.num}",
		success: function(result) {
			$("#commentList").html(result);
		}
	});
}
</script>

 

각 기능들을 Controller에 요청을 보냈습니다.

그럼 순차적으로 하나씩 처리합니다.


Controller

 

먼저 상세 화면 페이지 댓글 기능부터 구현하려고 합니다.

이전 포스팅에서 상세 화면 페이지에 아래 사진처럼 댓글 폼을 생성했습니다.

 

 

댓글 목록 출력 함수 먼저 기능 추가를 합니다.

 

 

기능이 하나씩 추가될 때 else if문 처리를 해서 구현해 주면 됩니다.

 

 

댓글 목록은 SQL에서 만든 BoradCommentDTO 타입으로 설정해서 리턴해줍니다.

다음으로 DAO에 요청 보낸. commentList() 작업을 해줍니다.


DAO

 

DAO 코드 구현을 할 때 주의할 점은 해당 타입을 맞춰서 구현을 해야 합니다.

댓글 목록 요청은 DTO 타입으로, DAO에서 구현할 때도 맞춰서 DTO 타입으로 해야 합니다.

 

 

댓글 목록 데이터 값을 가져와야 하기 때문에 selectList()를 사용하셔야 합니다.

다음으로 mapper 파일에 요청 보낸 "board.commentList"를 SQL문 처리를 해줍니다.

 


board.xml(mapper)

 

 

이전 포스팅에서 부터 말씀드린 것처럼 select는 꼭 resultType 설정을 해주셔야 합니다. 

댓글 목록은 DTO 타입으로 가져왔기 때문에 동일하게 DTO 타입으로 설정해 줍니다.

 

다음으로 Controller에서 출력 페이지 요청 보낸 comment_list 페이지를 생성합니다.


comment_list

 

comment_list 페이지는 상세 화면 페이지에서 ajax 방식으로 id="commentList"에 데이터 출력이 됩니다.(success 참고)

 

<%@ 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="../include/jquery-3.6.3.min.js"></script>
<%@ include file="../include/header.jsp" %>
</head>
<body>
<table border="1" style="width: 100%">
<c:forEach var="row" items="${list}">
 <tr>
  <td>
   ${row.writer}(<fmt:formatDate value="${row.reg_date}" 
   pattern="yyyy-MM-dd hh:mm:ss"/>)<br>
   ${row.content}
  </td>
 </tr>
</c:forEach>
</table>
</body>
</html>

 

댓글 목록 페이지는 마무리하고 결과를 확인하기 위해 댓글 추가 기능을 구현합니다.

 

댓글 쓰기 구현을 상세화면 페이지에서 자바 스크립트로 comment_add.do라는 요청을 보냈습니다.

그럼 Controller에서 추가로 기능 구현을 합니다.


Controller

 

댓글 추가 기능은 이름과 내용을 웹에서 받아서 데이터 추가를 해야 하기 때문에

 request 타입으로 생성해 주고 DTO에 담아줘서 DAO에 요청을 보냅니다.

 

 

DAO에 요청을 보냈으니 commentAdd(dto)를 생성합니다.


DAO

 

DAO에서는 추가로 구현할 건 없고 mapper로 요청을 보내는 코드만 구현해 주시면 됩니다.

 

 

요청을 보냈으니 mapper 파일로 이동합니다.

 


board.xml(mapper)

 

mapper에서는 insert문을 사용해서 해당 칼럼들을 작성하고 웹에서 작성하는 데이터를 넣어줘야 하기 때문에 values에서는 함수로 값을 받을 수 있게 합니다.

 

 

그럼 이제 결과를 확인합니다.


 결과 출력

 

 

<댓글 추가>

 

 

 

 

< 댓글 목록 리스트 >

 


마치며

 

오늘은 댓글 기능에 대해서 알아봤습니다. 

다음 포스팅은 수정/삭제 기능을 추가해 보겠습니다.

 

728x90