본문 바로가기
Java/Servlet & JSP

JSP) 게시글 및 첨부파일 삭제

by 박채니 2022. 7. 4.

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

 

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


게시글 및 첨부파일 삭제

 

boardView.jsp

<%
	Board board = (Board)request.getAttribute("board");
	List<Attachment> attachments = ((BoardExt) board).getAttachments();
%>
<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>
</section>
<% if(canEdit) { %>
	<form action="<%= request.getContextPath()%>/board/boardDelete" method="POST" name="boardDeleteFrm">
		<input type="hidden" name="no" value="<%= board.getNo() %>" />
	</form>
<script>
const deleteBoard = () => {
	if(confirm("정말 삭제하시겠습니까?")) {
		document.boardDeleteFrm.submit();
	}
};
<% } %>
</script>
<%@ include file="/WEB-INF/views/common/footer.jsp" %>

POST로 보내야 하기 때문에 form을 생성해주었고, input:hidden으로 no 값을 넘겨주었습니다.

 

Controller

BoardDeleteServlet

@WebServlet("/board/boardDelete")
public class BoardDeleteServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private BoardService boardService = new BoardService();
	
	/**
	 * 1. 저장된 첨부파일 조회 및 삭제 (java.io.File#delete)
	 * 2. board 삭제 (on delete cascade에 의해서 attachment 연쇄 삭제)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			int boardNo = Integer.parseInt(request.getParameter("no"));
			
			// 저장된 첨부파일 조회 및 서버에서 첨부파일삭제
			List<Attachment> attachments = boardService.findAttachmentByBoardNo(boardNo);
			if(attachments != null && !attachments.isEmpty()) {
				String saveDirectory = getServletContext().getRealPath("/upload/board");
				for(Attachment attach : attachments) {
					File delFile = new File(saveDirectory, attach.getRenamedFilename());
					delFile.delete();
				}
			}
			
			// board 삭제 (attachment 연쇄 삭제)
			int result = boardService.deleteBoard(boardNo);
			
			request.getSession().setAttribute("msg", "게시글을 성공적으로 삭제했습니다.");
			response.sendRedirect(request.getContextPath() + "/board/boardList");
		} catch(Exception e) {
			e.printStackTrace();
			throw e;
		}
	}
}

먼저 저장 되어 있는 첨부파일을 조회한 후, 서버 컴퓨터에 존재하는 첨부파일을 삭제해주었습니다.

File.delete() 메소드를 이용하였으며, 이 때 saveDirectory와 파일명을 넘겨주었습니다.

그 후 board테이블 레코드를 삭제 하였으며, on delete cascade에 의해서 attachment 테이블 또한 같이 삭제 됩니다.

 

Service

BoardService

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

 

Dao

BoardDao

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

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

 

해당 게시글 삭제 시

 

'Java > Servlet & JSP' 카테고리의 다른 글

JSP) 댓글, 대댓글 생성/나타내기  (0) 2022.07.06
JSP) 첨부파일 있는 게시글 수정  (0) 2022.07.05
JSP) 파일 다운로드  (0) 2022.07.04
JSP) 조회수 증가 처리  (0) 2022.07.04
JSP) XSS 공격 대비 - escape 처리  (0) 2022.07.03