댓글 목록 조회 기능 구현
특정 게시글에 등록된 댓글을 출력하는 기능을 구현해보자.
게시글의 경우, 게시글이 생성/수정/삭제되는 시점에 리스트 페이지로 리다이렉트 하도록 처리했다.
이와 달리 댓글은 생성/수정/삭제된 시점에 페이지를 이동하거나 새로고침 하지 않고, 테이블에서 SELECT 한 결과 데이터를 댓글 영역에 다시 렌더링 할 것이다.
1) 댓글 API 컨트롤러 메서드 추가하기
CommentApiController.java
// 댓글 리스트 조회
@GetMapping("/posts/{postId}/comments")
public List<CommentResponse> findAllComment(@PathVariable final Long postId) {
return commentService.findAllComment(postId);
}
해당 메서드는 특정 게시글(postId)에 등록된 모든 댓글을 조회한다.
2) 글 상세 페이지에 댓글 랜더링 영역 추가하기
view.html
<!--/* 댓글 렌더링 영역 */-->
<div class="cm_list">
</div>
3) 같은 페이지에 JS 함수 추가하기
view.html
window.onload = () => {
findAllComment();
}
// 전체 댓글 조회
function findAllComment() {
const postId = [[ ${post.id} ]];
$.ajax({
url : `/posts/${postId}/comments`,
type : 'get',
dataType : 'json',
async : false,
success : function (response) {
console.log(response);
},
error : function (request, status, error) {
console.log(error)
}
})
}
4) findAllComment 함수 수정하기
view.html
// 전체 댓글 조회
function findAllComment() {
const postId = [[ ${post.id} ]];
$.ajax({
url : `/posts/${postId}/comments`,
type : 'get',
dataType : 'json',
async : false,
success : function (response) {
// 1. 조회된 데이터가 없는 경우
if ( !response.length ) {
document.querySelector('.cm_list').innerHTML = '<div class="cm_none"><p>등록된 댓글이 없습니다.</p></div>';
return false;
}
// 2. 렌더링 할 HTML을 저장할 변수
let commentHtml = '';
// 3. 댓글 HTML 추가
response.forEach(row => {
commentHtml += `
<div>
<span class="writer_img"><img src="/images/default_profile.png" width="30" height="30" alt="기본 프로필 이미지"/></span>
<p class="writer">
<em>${row.writer}</em>
<span class="date">${dayjs(row.createdDate).format('YYYY-MM-DD HH:mm')}</span>
</p>
<div class="cont"><div class="txt_con">${row.content}</div></div>
<p class="func_btns">
<button type="button" class="btns"><span class="icons icon_modify">수정</span></button>
<button type="button" class="btns"><span class="icons icon_del">삭제</span></button>
</p>
</div>
`;
})
// 4. class가 "cm_list"인 요소를 찾아 HTML을 렌더링
document.querySelector('.cm_list').innerHTML = commentHtml;
},
error : function (request, status, error) {
console.log(error)
}
})
}
findAllComment( )의 response.forEach( )에서 row는 response에 담긴 각각의 댓글 객체를 의미.
response를 순환하며 commentHtml에 댓글 HTML을 추가한 후 div.cm_list에 렌더링 한다.
5) saveCommnet() 함수 수정하기
view.html
// 댓글 저장
function saveComment() {
const content = document.getElementById('content');
isValid(content, '댓글');
const postId = [[ ${post.id} ]];
const params = {
postId : postId,
content : content.value,
writer : '홍길동'
}
$.ajax({
url : `/posts/${postId}/comments`,
type : 'post',
contentType : 'application/json; charset=utf-8',
dataType : 'json',
data : JSON.stringify(params),
async : false,
success : function (response) {
alert('저장되었습니다.');
content.value = '';
document.getElementById('counter').innerText = '0/300자';
findAllComment();
},
error : function (request, status, error) {
console.log(error)
}
})
}
댓글 등록 시 저장되었다는 alert 메시지를 보이도록 변경.
또한 입력했던 댓글 내용과 입력된 자릿수를 초기화한 후 findAllComment( )를 호출해서 화면에 댓글을 다시 렌더링.
6) 댓글 등록 테스트
모든 코드는 아래 블로그를 참고합니다.
스프링 부트(Spring Boot) 게시판 - REST API 방식으로 댓글 리스트(목록) 기능 구현하기 [Thymeleaf, MariaDB
본 게시판 프로젝트는 단계별(step by step)로 진행되니, 이전 단계를 진행하시는 것을 권장드립니다. DBMS 툴은 DBeaver를 이용하며, DB는 MariaDB를 이용합니다. (MariaDB 설치하기) 화면 처리는 HTML5 기반
congsong.tistory.com
'SpringBoot 게시판 프로젝트' 카테고리의 다른 글
스프링부트(SpringBoot) 게시판 만들기 (17) - 댓글 삭제 기능 구현 (0) | 2024.07.22 |
---|---|
스프링부트(SpringBoot) 게시판 만들기 (16) - 댓글 수정 기능 구현 (0) | 2024.07.20 |
스프링부트(SpringBoot) 게시판 만들기 (14) - 댓글 등록 기능 구현 (0) | 2024.07.19 |
스프링부트(SpringBoot) 게시판 만들기 (12) - 페이징 & 검색 기능 구현 (0) | 2024.07.13 |
스프링부트(SpringBoot) 게시판 만들기 (11) - AOP와 트랜잭션 개념 (0) | 2024.07.08 |