기존 댓글 수정 기능 구현하기
모달(Modal)이라고 불리는 레이어 팝업(Layer Popup)을 이용해보자.
1) 댓글 API 컨트롤러에 메서드 추가하기
CommentApiController.java
// 댓글 상세정보 조회
@GetMapping("/posts/{postId}/comments/{id}")
public CommentResponse findCommentById(@PathVariable final Long postId, @PathVariable final Long id) {
return commentService.findCommentById(id);
}
// 기존 댓글 수정
@PatchMapping("/posts/{postId}/comments/{id}")
public CommentResponse updateComment(@PathVariable final Long postId, @PathVariable final Long id, @RequestBody final CommentRequest params) {
commentService.updateComment(params);
return commentService.findCommentById(id);
}
2) 레이어 팝업 HTML 추가하기
view.html
<!--/* 댓글 수정 popup */-->
<div id="commentUpdatePopup" class="popLayer">
<h3>댓글 수정</h3>
<div class="pop_container">
<table class="tb tb_row tl">
<colgroup>
<col style="width:30%;" /><col style="width:70%;" />
</colgroup>
<tbody>
<tr>
<th scope="row">작성자<span class="es">필수 입력</span></th>
<td><input type="text" id="modalWriter" name="modalWriter" placeholder="작성자를 입력해 주세요." /></td>
</tr>
<tr>
<th scope="row">내용<span class="es">필수 입력</span></th>
<td><textarea id="modalContent" name="modalContent" cols="90" rows="10" placeholder="수정할 내용을 입력해 주세요."></textarea></td>
</tr>
</tbody>
</table>
<p class="btn_set">
<button type="button" id="commentUpdateBtn" class="btns btn_st2">수정</button>
<button type="button" class="btns btn_bdr2" onclick="closeCommentUpdatePopup();">취소</button>
</p>
</div>
<button type="button" class="btn_close" onclick="closeCommentUpdatePopup();"><span><i class="far fa-times-circle"></i></span></button>
</div>
3) 레이어 팝업 관련 JS 추가하기
view.html
// 댓글 수정 팝업 open
function openCommentUpdatePopup(id) {
const postId = [[ ${post.id} ]];
$.ajax({
url : `/posts/${postId}/comments/${id}`,
type : 'get',
dataType : 'json',
async : false,
success : function (response) {
document.getElementById('modalWriter').value = response.writer;
document.getElementById('modalContent').value = response.content;
document.getElementById('commentUpdateBtn').setAttribute('onclick', `updateComment(${id})`);
layerPop('commentUpdatePopup');
},
error : function (request, status, error) {
console.log(error)
}
})
}
// 댓글 수정 팝업 close
function closeCommentUpdatePopup() {
document.querySelectorAll('#modalContent, #modalWriter').forEach(element => element.value = '');
document.getElementById('commentUpdateBtn').removeAttribute('onclick');
layerPopClose('commentUpdatePopup');
}
4) findAllComment() 함수 수정하기
view.html
<p class="func_btns">
<button type="button" onclick="openCommentUpdatePopup(${row.id});" class="btns"><span class="icons icon_modify">수정</span></button>
<button type="button" class="btns"><span class="icons icon_del">삭제</span></button>
</p>
수정 버튼을 클릭 했을 때 레이어 팝업이 오픈 될 수 있도록 클릭 이벤트 선언.
5) updateComment() 함수 작성하기
레이어 팝업의 수정 버튼을 클릭 했을 때의 이벤트 함수 작성
// 댓글 수정
function updateComment(id) {
const writer = document.getElementById('modalWriter');
const content = document.getElementById('modalContent');
isValid(writer, '작성자');
isValid(content, '수정할 내용');
const postId = [[ ${post.id} ]];
const params = {
id : id,
postId : postId,
content : content.value,
writer : writer.value
}
$.ajax({
url : `/posts/${postId}/comments/${id}`,
type : 'patch',
contentType : 'application/json; charset=utf-8',
dataType : 'json',
data : JSON.stringify(params),
async : false,
success : function (response) {
alert('수정되었습니다.');
closeCommentUpdatePopup();
findAllComment();
},
error : function (request, status, error) {
console.log(error)
}
})
}
saveComment( )와 유사한 기능을 하는 함수이다.
해당 함수는 파라미터로 댓글의 id를 전달받아 서버로 함께 전송하며, 댓글 수정이 완료되면 레이어 팝업을 닫은 후 댓글을 다시 조회한다.
모든 코드는 아래 블로그 참고합니다!
스프링 부트(Spring Boot) 게시판 - REST API 방식으로 댓글 수정 기능 구현하기 [Thymeleaf, MariaDB, IntelliJ,
본 게시판 프로젝트는 단계별(step by step)로 진행되니, 이전 단계를 진행하시는 것을 권장드립니다. DBMS 툴은 DBeaver를 이용하며, DB는 MariaDB를 이용합니다. (MariaDB 설치하기) 화면 처리는 HTML5 기반
congsong.tistory.com
'SpringBoot 게시판 프로젝트' 카테고리의 다른 글
스프링부트(SpringBoot) 게시판 만들기 (18) - 댓글 페이징 기능 구현 (1) | 2024.07.22 |
---|---|
스프링부트(SpringBoot) 게시판 만들기 (17) - 댓글 삭제 기능 구현 (0) | 2024.07.22 |
스프링부트(SpringBoot) 게시판만들기 (15) - 댓글 목록 조회 기능 구현 (0) | 2024.07.20 |
스프링부트(SpringBoot) 게시판 만들기 (14) - 댓글 등록 기능 구현 (0) | 2024.07.19 |
스프링부트(SpringBoot) 게시판 만들기 (12) - 페이징 & 검색 기능 구현 (0) | 2024.07.13 |