SpringBoot 게시판 프로젝트

스프링부트(SpringBoot) 게시판 만들기 (17) - 댓글 삭제 기능 구현

얼뚱인데요 2024. 7. 22. 18:25
댓글 삭제 기능 구현하기

 

1) 댓글 컨트롤러에 메서드 추가하기

 

CommentApiController.java

    // 댓글 삭제
    @DeleteMapping("/posts/{postId}/comments/{id}")
    public Long deleteComment(@PathVariable final Long postId, @PathVariable final Long id) {
        return commentService.deleteComment(id);
    }

 

특정 게시글(postId)에 등록된 모든 댓글 중 PK(id)에 해당되는 댓글을 삭제한다.

삭제 프로세스가 완료되면 삭제된 댓글의 PK(id)를 리턴한다.

 

 

 

2) 상세 페이지에 findAllComment() 함수 수정하기

 

view.html

    <button type="button" onclick="deleteComment(${row.id});" class="btns"><span class="icons icon_del">삭제</span></button>

 

댓글 랜더링 html 부분의 삭제 버튼에 onclick 이벤트 추가

 

 

3) 상세 페이지에 deleteComment() 함수 생성하기

 

view.html

    // 댓글 삭제
    function deleteComment(id) {

        if ( !confirm('선택하신 댓글을 삭제할까요?') ) {
            return false;
        }
        
        const postId = [[ ${post.id} ]];

        $.ajax({
            url : `/posts/${postId}/comments/${id}`,
            type : 'delete',
            dataType : 'json',
            async : false,
            success : function (response) {
                alert('삭제되었습니다.');
                findAllComment();
            },
            error : function (request, status, error) {
                console.log(error)
            }
        })
    }

 

CommentApiController의 deleteComment( )를 호출해서 댓글을 삭제 처리한다.

게시글과 마찬가지로 delete_yn 칼럼의 상태값을 변경하는 논리 삭제 방식이며, 삭제가 완료되면 findAllComment( )로 댓글을 다시 조회한다.

 

 

맨 첫 번째 댓글의 삭제 버튼 클릭 시

 

 

이전 confirm 창 확인 클릭 결과

 

첫 번째 댓글이 없어진 것을 확인 할 수 있다.

 

 

첫 번째 댓글의 delete_yn 상태 값이 1로 변경 된 것을 확인 가능

 

 


모든 코드는 아래 블로그를 참고합니다.

 

스프링 부트(Spring Boot) 게시판 - REST API 방식으로 댓글 삭제 기능 구현하기 [Thymeleaf, MariaDB, IntelliJ,

본 게시판 프로젝트는 단계별(step by step)로 진행되니, 이전 단계를 진행하시는 것을 권장드립니다. DBMS 툴은 DBeaver를 이용하며, DB는 MariaDB를 이용합니다. (MariaDB 설치하기) 화면 처리는 HTML5 기반

congsong.tistory.com