게시글 삭제
<button id="deleteBtn">삭제</button>
// 즉시 실행 함수 : 성능 up(속도), 변수명 중복 X
(function(){
const deleteBtn = document.getElementById("deleteBtn"); // 존재하지 않으면 null
if(deleteBtn != null) { // 버튼이 화면에 존재할 때만
deleteBtn.addEventListener("click", function(){
// 현재 : /community/board/detail?no=1111&cp=1&type=1
// 목표 : /community/board/delete?no=1111&type=1
// 상대경로 : delete?no=1111&type=1
let url = "delete"; // 상대경로로 작성
// 주소에 작성된 쿼리스트링에서 필요한 파라미터만 얻어와서 사용
// 1) 쿼리스트링에 존재하는 파라미터 모두 얻어오기
// location.href : 현재 페이지 주소(http://~)
const params = new URL(location.href).searchParams; // 파라미터만 뽑아서 저장
// 자바스크립트 내장 객체
// 2) 원하는 파라미터만 얻어 와 변수에 저장
const no = "?no=" + params.get("no"); // ?no=1111
const type = "&type=" + params.get("type"); // &type=1
// url에 쿼리스트링 추가
url += no + type // delete?no=1111&type=1
if(confirm("정말 삭제하시겠습니까?")){
location.href = url; // get방식으로 url에 요청
}
})
}
})();
package edu.kh.community.board.controller;
import java.io.IOException;
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) { // 성공
System.out.println(result);
message = "게시글이 삭제되었습니다.";
path = "list?type=" + type; // 해당 게시판 목록 1페이지
} else { // 실패
message = "게시글 삭제 실패";
path = req.getHeader("referer");
// 상세 페이지 == 이전 요청 페이지 주소 == referer
}
session.setAttribute("message", message);
resp.sendRedirect(path);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/** 게시글 삭제 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;
}
/** 게시글 삭제 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;
}
<!-- 게시글 삭제 -->
<entry key="deleteBoard">
UPDATE BOARD
SET BOARD_ST = 'Y'
WHERE BOARD_NO=?
</entry>