본문 바로가기
Java/Servlet & JSP

JSP) 댓글 삭제 기능

by 박채니 2022. 7. 6.

안녕하세요, 코린이의 코딩 학습기 채니 입니다.

 

개인 포스팅용으로 내용에 오류 및 잘못된 정보가 있을 수 있습니다.


댓글 삭제 기능

 

boardView.jsp

<%@ include file="/WEB-INF/views/common/header.jsp" %>
<%
	Board board = (Board)request.getAttribute("board");
	List<Attachment> attachments = ((BoardExt) board).getAttachments();
	List<BoardComment> commentList = (List<BoardComment>)request.getAttribute("commentList");
%>
<link rel="stylesheet" href="<%=request.getContextPath()%>/css/board.css" />
<section id="board-container">
	<h2>게시판</h2>
	<table id="tbl-board-view">
		<tr>
			<th>글번호</th>
			<td><%= board.getNo() %></td>
		</tr>
		<tr>
			<th>제 목</th>
			<td><%= board.getTitle() %></td>
		</tr>
		<tr>
			<th>작성자</th>
			<td><%= board.getWriter() %></td>
		</tr>
		<tr>
			<th>조회수</th>
			<td><%= board.getReadCount() %></td>
		</tr>
			<% if(attachments != null && !attachments.isEmpty()) {
				for(Attachment attach : attachments) { %>
		<tr>
			<th>첨부파일</th>
			<td>
				<%-- 첨부파일이 있을경우만, 이미지와 함께 original파일명 표시 --%>
				<img alt="첨부파일" src="<%=request.getContextPath() %>/images/file.png" width=16px>
				<a href="<%= request.getContextPath()%>/board/fileDownload?no=<%=attach.getNo()%>"><%= attach.getOriginalFilename() %></a>
			</td>
		</tr>
			<% 	}
			} %>
		<tr>
			<th>내 용</th>
			<td><%= board.getContent() %></td>
		</tr>
		<% 
		boolean canEdit = loginMember != null && (loginMember.getMemberId().equals(board.getWriter()) || loginMember.getMemberRole() == MemberRole.A);
		if(canEdit) { %>
		<tr>
			<%-- 작성자와 관리자만 마지막행 수정/삭제버튼이 보일수 있게 할 것 --%>
			<th colspan="2">
				<input type="button" value="수정하기" onclick="updateBoard()">
				<input type="button" value="삭제하기" onclick="deleteBoard()">
			</th>
		</tr>
		<% } %>
	</table>
	
	    <hr style="margin-top:30px;" />    
    
    <div class="comment-container">
    	<!-- 댓글 작성부 -->
        <div class="comment-editor">
            <form
            action="<%=request.getContextPath()%>/board/boardCommentEnroll" method="post" name="boardCommentFrm">
                <input type="hidden" name="boardNo" value="<%= board.getNo() %>" />
                <input type="hidden" name="writer" value="<%= loginMember != null ? loginMember.getMemberId() : "" %>" />
                <input type="hidden" name="commentLevel" value="1" />
                <input type="hidden" name="commentRef" value="0" />    
                <textarea name="content" cols="60" rows="3"></textarea>
                <button type="submit" id="btn-comment-enroll1">등록</button>
            </form>
        </div>
        <!--table#tbl-comment-->
        <table id="tbl-comment">
		<% if(commentList != null && !commentList.isEmpty()) {
			SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd HH:mm");
			for(BoardComment comment : commentList) { 			
				boolean canDelete = loginMember != null && (loginMember.getMemberId().equals(comment.getWriter()) || loginMember.getMemberRole() == MemberRole.A);        	
			%>
       		<tr class="<%= comment.getCommentLevel() == CommentLevel.COMMENT ? "level1" : "level2" %>">
       			<td>
       				<sub class="comment-writer"><%= comment.getWriter() %></sub>
       				<sub class="comment-date"><%= sdf.format(comment.getRegDate()) %></sub>
       				<div>
       					<%= comment.getContent() %>
       				</div>
       			</td>
       			<td>
  			        <% if(comment.getCommentLevel() == CommentLevel.COMMENT) { %>
        			<button class="btn-reply" value="<%=comment.getNo() %>">답글</button>
        			<% } %>
        			
       				<% if(canDelete) { %>
       				<button class="btn-delete" value="<%= comment.getNo() %>">삭제</button>
       				<% } %>
       			</td>
        	</tr>
      			<% 	}
			} %>
        </table>
    </div>
</section>
<form action="<%= request.getContextPath() %>/board/boardCommentDelete" method="POST" name="boardCommentDelFrm">
	<input type="hidden" name="no" />
</form>
<script>
document.querySelectorAll(".btn-delete").forEach((btn) => {
	btn.addEventListener('click', (e) => {
		if(confirm("해당 댓글을 정말 삭제하시겠습니까?")) {
			const {value} = e.target;
			const frm = document.boardCommentDelFrm;
			frm.no.value = value;
			frm.submit();
		}
	})
});

DML의 경우 반드시 POST 요청을 해야하므로, 폼을 생성해주었으며 input:hidden으로 no를 name값을 넘겨주어 꺼내사용할 수 있도록 하였습니다.

 

Controller

BoardCommentDeleteServlet

@WebServlet("/board/boardCommentDelete")
public class BoardCommentDeleteServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private BoardService boardService = new BoardService();	

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			int no = Integer.parseInt(request.getParameter("no"));
			
			int result = boardService.deleteBoardCommentByNo(no);
			
			response.sendRedirect(request.getHeader("Referer"));
		} catch(Exception e) {
			e.printStackTrace();
			throw e;
		}
	}
}

 

Service

BoardService

public int deleteBoardCommentByNo(int no) {
    Connection conn = getConnection();
    int result = 0;
    try {
        result = boardDao.deleteBoardCommentByNo(conn, no);
        commit(conn);
    } catch(Exception e) {
        rollback(conn);
        throw e;
    } finally {
        close(conn);
    }
    return result;
}

 

Dao

BoardDao

// deleteBoardCommentByNo = delete from board_comment where no = ?
public int deleteBoardCommentByNo(Connection conn, int no) {
    PreparedStatement pstmt = null;
    int result = 0;
    String sql = prop.getProperty("deleteBoardCommentByNo");

    try {
        pstmt = conn.prepareStatement(sql);
        pstmt.setInt(1, no);
        result = pstmt.executeUpdate();
    } catch (SQLException e) {
        throw new BoardException("댓글/답글 삭제 오류!", e);
    } finally {
        close(conn);
    }
    return result;
}