커뮤니티 - 게시글 삭제 기능 구현 (23.07.28)

·2023년 7월 28일
0

Server

목록 보기
33/35
post-thumbnail

📝 게시글 삭제 기능


💡 VS Code

🔎 board.js

// 즉시 실행 함수 : 성능 up, 변수명 중복 X
(function(){

    const deleteBtn = document.getElementById("deleteBtn"); // 존재하지 않으면 null

    if(deleteBtn != null){ // 버튼이 화면에 존재할 때
        deleteBtn.addEventListener("click", function(){
            // 현재 : detail?no=1562&cp=1&type=1

            // 목표 : delete?no=1562&type=1

            let url = "delete"; // 상대경로 형식으로 작성

            // 주소에 작성된 쿼리스트링에서 필요한 파라미터만 얻어와서 사용

            // 1) 쿼리스트링에 존재하는 파라미터 모두 얻어오기
            const params = new URL(location.href).searchParams;

            // 2) 원하는 파라미터만 얻어와서 변수에 저장
            const no = "?no=" + params.get("no"); // ?np=1562

            const type = "&type=" + params.get("type"); // &type=1

            // url에 쿼리스트링 추가
            url += no + type; // delete?no=1562&type=1

            if(confirm("정말로 삭제하시겠습니까?")){
                location.href = url; // get방식으로 url에 요청
            }
        })
    }

})();

💡 Eclipse

🔎 BoardDeleteServlet.java

package edu.kh.community.board.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import edu.kh.community.board.model.service.BoardService;

@WebServlet("/board/delete")
public class BoardDeleteServlet extends HttpServlet {
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		try {
			int type = Integer.parseInt(req.getParameter("type"));
			int boardNo = Integer.parseInt(req.getParameter("no"));
			
			int result = new BoardService().deleteBoard(boardNo);
			
			HttpSession session = req.getSession();
			String path = null;
			String message = null;
			
			if(result > 0) { // 성공
				message = "게시글이 삭제되었습니다.";
				path = "list?type=" + type; // 해당 게시판 목록 1페이지
					// list?type=2
				
			} else { // 실패
				message = "게시글 삭제에 실패했습니다.";
				path = req.getHeader("referer");
				// 상세 페이지 == 이전 요청 페이지 주소 == referer
			}
			
			session.setAttribute("message", message);

			resp.sendRedirect(path);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

🔎 BoardService.java

	/** 게시글 삭제 Service
	 * @param boardNo
	 * @return result
	 * @throws Exception
	 */
	public int deleteBoard(int boardNo) throws Exception {
		
		Connection conn = getConnection();
		
		int result = dao.deleteBoard(conn, boardNo);
		
		if(result > 0) commit(conn);
		else		   rollback(conn);
		
		close(conn);
		
		return result;
	}

🔎 BoardDAO.java

	/** 게시글 삭제 DAO
	 * @param conn
	 * @param boardNo
	 * @return result
	 * @throws Exception
	 */
	public int deleteBoard(Connection conn, int boardNo) throws Exception {
		
		int result = 0;
		
		try {
			
			String sql = prop.getProperty("deleteBoard");
			
			pstmt = conn.prepareStatement(sql);
			
			pstmt.setInt(1, boardNo);
			
			result = pstmt.executeUpdate();
			
		} finally {
			close(pstmt);
		}
		
		return result;
	}

🔎 board-sql.xml

	<!-- 게시글 삭제 -->
	<entry key="deleteBoard">
		UPDATE BOARD SET
		BOARD_ST = 'Y'
		WHERE BOARD_NO = ?
	</entry>

profile
풀스택 개발자 기록집 📁

0개의 댓글