[홈페이지 제작] 홈페이지 댓글 만들기 5 - 댓글 삭제

Feb 20, 2024
[홈페이지 제작] 홈페이지 댓글 만들기 5 - 댓글 삭제
 

1. View

 
notion image
휴지통 버튼을 누르면 삭제가 실행된다.
 
<!-- 댓글아이템 --> {{#replyList}} <div class="list-group-item d-flex justify-content-between align-items-center"> <div class="d-flex"> <div class="px-1 me-1 bg-primary text-white rounded">{{username}}</div> <div>{{comment}}</div> </div> <!--댓글 삭제 --> {{#replyOwner}} <form action="/reply/{{id}}/delete" method="post"> <button class="btn">🗑</button> </form> {{/replyOwner}} </div> {{/replyList}}
 
form 태그 내부에 댓글 삭제 버튼을 만든다.
 
삭제는 댓글 번호를 통해 삭제를 한다. /reply/{{id}}/delete
 
BoardResponse 를 통해 전달받은 댓글의 id 를 변수로 할용한다.
 
notion image
 

2. 컨트롤러

reply/ReplyController
@PostMapping("/reply/{id}/delete") public String delete(@PathVariable int id,HttpServletRequest request){ //로그인 확인 User sessionUser = (User) session.getAttribute("sessionUser"); if(sessionUser==null){ return "redirect:/loginForm"; } Reply reply = replyRepository.findById(id); if(reply==null){ request.setAttribute("msg","페이지를 찾을 수 없습니다."); request.setAttribute("status",404); return "error/40x"; } if(reply.getUserId()!=sessionUser.getId()){ request.setAttribute("msg","권한이 없습니다."); request.setAttribute("status",403); return "error/40x"; } replyRepository.deleteById(id); return "redirect:/board/"+reply.getBoardId(); }
 
 

3. 레파지토리

 
reply/ReplyRepository
public Reply findById(int id) { //select 문은 Reply.class 클래스명을 작성해야 파싱 가능 Query query = em.createNativeQuery("select * from reply_tb where id =?",Reply.class); query.setParameter(1,id); try { return (Reply) query.getSingleResult(); }catch (Exception e){ return null ; } }
 
댓글 번호로 댓글이 존재하는지 여부를 확인한다.
 
💡
삭제 전 데이터를 먼저 확인하면 잘못된 데이터 삭제나 중복 삭제를 방지하여 데이터의 무결성을 유지할 수 있다.
 
reply/ReplyRepository
@Transactional public void deleteById(int id) { Query query = em.createNativeQuery("delete from reply_tb where id = ?"); query.setParameter(1,id); query.executeUpdate(); }
 
댓글 번호로 게시글을 삭제한다.
 
notion image
 
notion image
 
댓글이 삭제되었다.
 
notion image
 
DB에서도 데이터가 삭제된 것을 확인할 수 있다.
Share article
RSSPowered by inblog