Servlet/JSP 답변형 게시판 만들기 - 삭제

코코·2020년 8월 17일
0

com.test.dao.BoardDAOTest

    @Test
    public void deleteTest() throws ClassNotFoundException {
    	Class.forName(DRIVER);
    	String sql = "DELETE FROM t_board WHERE bno = ?";
    	log.info(sql);
    	
    	try(
        	Connection conn = DriverManager.getConnection(URL,USER,PW);
        	PreparedStatement pstmt = conn.prepareStatement(sql);
        	) {
    		
    		assertNotNull(conn);
    		
    		pstmt.setInt(1, 44);
    		
    		assertTrue(pstmt.executeUpdate()==1);
        	
        	} catch(Exception e) {
        		e.printStackTrace();
        	}
       }

com.coco.dao.BoardDAO

	public int delete(int bno) {
    	String sql = "DELETE FROM t_board WHERE bno = ?";
    	log.info(sql);
    	try(
            Connection conn = ds.getConnection();
            PreparedStatement pstmt = conn.prepareStatement(sql);
            ) {
        		
        	pstmt.setInt(1, bno);
        		
        	return pstmt.executeUpdate();
            	
    	} catch(Exception e) {
    		e.printStackTrace();
        }
    	
    	return -1;
	} //delete()

com.coco.service.BoardServiceImpl

package com.coco.service;

import java.util.List;

import com.coco.dao.BoardDAO;
import com.coco.vo.BoardVO;

public class BoardServiceImpl implements BoardService {

	private BoardDAO dao;
	
	public BoardServiceImpl() {
		//초기화
		dao = new BoardDAO();
	}
	
	...
  	...
    
	@Override
	public int remove(int bno) {
		return dao.delete(bno);
	}
}

com.coco.controller.BoardController



	private void doHandle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		BoardService boardService = new BoardServiceImpl();
		String nextPage = "";
		String action = request.getPathInfo();	//어떤 url을 요청했는가?
		List<BoardVO> list;
		log.info("action : " + action);
		
        ...생략
        
		 else if (action.equals("/remove")) {
			int bno = Integer.parseInt(request.getParameter("bno"));
			log.info("bno : " + bno);

			int removeResult = boardService.remove(bno);
			
			String msg = removeResult==1 ? "success" : "fail";
			
			//list페이지로 성공 여부 메세지를 보낸다.
			//성공하면 list창에 alert창을 띄워 삭제했다는 메세지를 띄운다.
			request.setAttribute("result", msg);
			nextPage ="/board/list";
		}
		
		RequestDispatcher dispatcher = request.getRequestDispatcher(nextPage);
		dispatcher.forward(request, response);
	}
}

post.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>[${post.bno}번 게시물] ${post.title }</title>
</head>
<body>
<h1>게시물 조회</h1>
<form id='action'>
	<table>
		<tr>
			<td width="20%" align="center"> 제목 </td>
			<td> <input type='text' id='title' name='title' value='${post.title }' disabled></td>
		</tr>
		<tr>
			<td width="20%" align="center"> 내용 </td>
			<td>
				<textarea rows="20" cols="60" id='content' name='content' disabled>${post.content }</textarea>
			</td>
		</tr>
		<tr>
			<td width="20%" align="center"> 작성자 </td> 
			<td><input type='text' id='id' name='id' value='${post.id }' disabled></td> 
		</tr>
		<tr id="modBtn" style='display:none;'>
	    	<td colspan="2"   align="center" >
	        <input type=button id='mod' value="수정 완료">
         	<input type=button id='back' value="취소">
	   		</td>   
 		</tr>
		<tr id="btn">
			<td colspan="2" align="center">
			<input type='button' id='modify' value='수정'>
			<input type='button' id='remove' value='삭제'> 
			<input type='button' id='list' value='목록'>
			<input type='button' id='rePost' value='답글'></td> 
		</tr>
	</table>
	
	<input type='hidden' id='bno' name='bno' value='${post.bno }'>
	</form>
	
<script>
	window.onload = () => {
		const remove = document.getElementById('remove')
		const list = document.getElementById('list')
		const rePost = document.getElementById('rePost')
		const modify = document.getElementById('modify')
		const actionForm = document.getElementById('action')
		
		console.log(remove)
		console.log(list)
		console.log(rePost)

		//목록으로
		list.addEventListener("click", () => {
			location.replace('/board/list')
		})
		
		//수정 버튼 이벤트
		modify.addEventListener("click", ()=>{
			document.getElementById('title').disabled=false
			document.getElementById('content').disabled=false
			document.getElementById("modBtn").style.display="block"
			document.getElementById('btn').style.display="none"
			
		})
		
		//수정 완료
		document.getElementById('mod').addEventListener("click", () => {
			actionForm.action = '/board/modify'
			actionForm.method = 'post'
			actionForm.submit();
		})
		
		//수정 취소
		document.getElementById('back').addEventListener("click", () => {
			document.getElementById('btn').style.display="block"
			document.getElementById("modBtn").style.display="none";
			document.getElementById('content').disabled=true
			document.getElementById('title').disabled=true
		})
		
		//삭제
		remove.addEventListener("click", () => {
			if(!confirm("삭제하겠습니까?")) { return; }
			else{
				actionForm.action = '/board/remove'
				actionForm.method = 'post'
				actionForm.submit()
			}
		}) 
	}
</script>
</body>
</html>

list.jsp 추가 부분

게시물 삭제 시, 컨트롤러에서 성공 여부를 list페이지로 보내면,
list페이지는 그 결과를 받아서 화면에 뿌린다.

<script>
	window.onload = () => {
		const removeResult = '${result }'
		if(removeResult == 'success') {
			alert('삭제 되었습니다.')
		} else if(removeResult=='fail') {
			alert('다시 시도하세요');
			return;
		}
	}
</script>

alert사용은 모든 작업을 중지하기 때문에 권장되지 않는다. 모달창을 띄우는 게 더 나은 방법일 것이다.

0개의 댓글