21.02.18 JSPCommunity 프로젝트(댓글 등록 ajax화, 댓글 리스트 ajax로 불러오기 성공, 페이징 시도중)

2021. 2. 18. 23:24JAVA/JSP Community 사이트 프로젝트

<댓글 등록 JS>

<script>

let replyForm_submited = false;

		function ArticleWriteReplyForm__submit(form) {
			form.replyBody.value = form.replyBody.value.trim();

			if(replyForm_submited){

				alert('처리중입니다.');
					return;
			}
			
			if (form.replyBody.value.length == 0) {
				alert('댓글을 입력해주세요.');
				form.replyBody.focus();
				return;
			}
			
			$.post(
				'replyAjax',
				 {
				id : form.articleId.value,
				body : form.replyBody.value
			}, 
			function(data) {
				alert(data.msg);
			}, 
			'json'
			);
			form.replyBody.value = '';
			replyForm_submited = true;
		};
	</script>

<댓글 등록 java>

<div class="reply-write-box">
        <form class="reply-write-box-form flex flex-jc-c flex-ai-c" name="form" onsubmit="ArticleWriteReplyForm__submit(this); return false;" action="replyAjax" method="POST">
          <input type="hidden" name="articleId" value="${article.id}">
         
          <input type="hidden" name="redirectUrl"
				value="${Util.getNewUrl(currentUrl, 'focusReplyId', '[NEW_REPLY_ID]')}" />
          <span><i class="far fa-comment-dots"></i></span>
          <input type="text" name="replyBody" placeholder="댓글 입력">
          <div class="reply-write-box-form__option ">
            <button class="btn btn-go" type="submit"><i class="fas fa-pen"></i> 등록</button>
          </div>
        </form>
      </div>

<댓글 리스팅 JS>

<script>
	var ArticleReplyList__$box = $('.reply-list-box');
	var ArticleReplyList__$replyBox = ArticleReplyList__$box.find('.reply-box');
	var ArticleReplyList__$replyPageBox = $('.reply-page-menu-section2');
	var ArticleReplyList__$replyPageBtnBox = ArticleReplyList__$replyPageBox.find('.reply-page-menu');
	var ArticleReplyList__lastLoadedId = 0;
	
	function ArticleReplyList__loadMore() {
		
		$.get(
			'getReplies', 
			
			{
				articleId : ${article.id},
				lastLoadedId : ArticleReplyList__lastLoadedId + 1
			}, 

			function(data) {
				
				
			if ( data.body.replies && data.body.replies.length > 0) {
				ArticleReplyList__lastLoadedId = data.body.replies[data.body.replies.length - 1].id;
				ArticleReplyList__drawReplies(data.body.replies, data.body.totalCount, data.body.page);
			}

			setTimeout(ArticleReplyList__loadMore, 5000);
		}, 

		'json'

		);
	}
	function ArticleReplyList__drawReplies(replies, totalCount, page) {
		
		// 페이징
		var repliesInAPage = 5;
		// 한 메인페이지 화면에 나올 하단 페이지 메뉴 버튼 수 ex) 1 2 3 4 5 6 7 8 9 10
		var pageMenuBoxSize = 3;
		var totalRepliesCount = totalCount; // 전체 reply의 수 카운팅
		var totalPages = Math.ceil(totalRepliesCount / repliesInAPage);
		
		// 총 필요 페이지 수까지
		buildReplyListPage(replies, repliesInAPage, pageMenuBoxSize, totalPages, page);


	}
	function buildReplyListPage(replies, repliesInAPage, pageMenuBoxSize, totalPages, page){
		
		var startPoint = (page - 1) * repliesInAPage; // page=1일때 index=0(즉,id = 1) 2 10(11) 3 20(21)
		var endPoint = startPoint + repliesInAPage - 1; // page=1일때 index0~9 -> id1~10
		
		if (endPoint >= replies.length) {
			endPoint = replies.length;
		}
		
		for ( var i = startPoint; i <= endPoint; i++ ) {
			var reply = replies[i];
			ArticleReplyList__drawReply(reply);
			
		}
		
		var previousPageNumCount = (page - 1) / pageMenuBoxSize; // 현재 페이지가 2이면 previousPageNumCount = 1/5
		var boxStartNum = pageMenuBoxSize * previousPageNumCount + 1; // 총 페이지 수 30이면 1~5 6~10 11~15
		var boxEndNum = pageMenuBoxSize + boxStartNum - 1;

		if (boxEndNum > totalPages) {
			boxEndNum = totalPages;
		}

		
		
		// 2. '이전','다음' 버튼 페이지 계산
		var boxStartNumBeforePage = boxStartNum - 1;
		if (boxStartNumBeforePage < 1) {
			boxStartNumBeforePage = 1;
		}
		var boxEndNumAfterPage = boxEndNum + 1;
		if (boxEndNumAfterPage > totalPages) {
			boxEndNumAfterPage = totalPages;
		}

		
		
		// 3. '이전','다음' 버튼 필요 유무 판별
		var boxStartNumBeforePageBtnNeedToShow = boxStartNumBeforePage != boxStartNum;
		var boxEndNumAfterPageBtnNeedToShow = boxEndNumAfterPage !== boxEndNum;
		
		
		buildReplyPageBtn(boxStartNumBeforePageBtnNeedToShow, boxEndNumAfterPageBtnNeedToShow, boxStartNum, boxEndNum, page);

	}
	
	function ArticleReplyList__drawReply(reply) {
		var html = '';
		html += '<div class="reply-list-box-writer"><i class="far fa-user-circle"></i> ' + reply.extra_memberNickname + '</div>';
		html += '<div class="reply-list-box__cell flex flex-jc-sb"><div class="reply-list-box__cell-contents flex flex-ai-c">';

		html += '<div class="reply-list-box__cell-updateDate">' + reply.updateDate + '</div>';
		html += '<div data-id="${reply.id}" class="reply-list-box__cell-body">' + reply.body + '</div>';
		html += '</div>';
		
		html += '<div class="reply-list-box-cell__option"><div class="reply-detail-cell-likesCount flex">';
		html += '<c:if test="${isLogined == false}">';
		html += '<button class="addLike" type="button" onclick="alert(\'로그인 후 이용해 주세요.\')"><i class="far fa-thumbs-up"></i>&nbsp;<span class="likesCount">' + reply.extra_likeOnlyPoint + '</span></button>';
		html += '<button class="addUnLike" type="button" onclick="alert(\'로그인 후 이용해 주세요.\')"><i class="far fa-thumbs-down"></i>&nbsp;<span class="unLikesCount">' + reply.extra_dislikeOnlyPoint + '</span></button>';
		html += '</c:if>';
		html += '<c:if test="${reply.extra.actorCanLike}">';
		html += '<button class="addLike" type="button"><a href="../like/doLike?relTypeCode=reply&relId=${reply.id}&redirectUrl=${encodedCurrentUrl}" onclick="if ( !confirm(\'`좋아요` 처리 하시겠습니까?\') ) return false;"><i class="far fa-thumbs-up"></i>&nbsp;<span class="likesCount">' + reply.extra_likeOnlyPoint + '</span></a></button>';
		html += '</c:if>';
		html += '<c:if test="${reply.extra.actorCanCancelLike}">';
		html += '<button class="addLike" type="button"><a href="../like/doCancelLike?relTypeCode=reply&relId=${reply.id}&redirectUrl=${encodedCurrentUrl}" onclick="if ( !confirm(\'`좋아요`를 취소 처리 하시겠습니까?\') ) return false;"><i class="fas fa-thumbs-up"></i>&nbsp;<span class="likesCount">' + reply.extra_likeOnlyPoint + '</span></a></button>';
		html += '</c:if>';		
		html += '<c:if test="${reply.extra.actorCanDislike}">';
		html += '<button class="addUnLike" type="button"><a href="../like/doDislike?relTypeCode=reply&relId=${reply.id}&redirectUrl=${encodedCurrentUrl}" onclick="if ( !confirm(\'`싫어요` 처리 하시겠습니까?\') ) return false;"><i class="far fa-thumbs-down"></i>&nbsp;<span class="unLikesCount">' + reply.extra_dislikeOnlyPoint + '</span></a></button>';
		html += '</c:if>';
		html += '<c:if test="${reply.extra.actorCanCancelDislike}">';
		html += '<button class="addUnLike" type="button"><a href="../like/doCancelDislike?relTypeCode=reply&relId=${reply.id}&redirectUrl=${encodedCurrentUrl}" onclick="if ( !confirm(\'`싫어요`를 취소 처리 하시겠습니까?\') ) return false;"><i class="fas fa-thumbs-down"></i>&nbsp;<span class="unLikesCount">' + reply.extra_dislikeOnlyPoint + '</span></a></button>';
		html += '</c:if>';
		
    	  html += '</div>';

		html += '</div>';
		html += '</div>';

		
		ArticleReplyList__$replyBox.prepend(html);
	}
	
	function buildReplyPageBtn(boxStartNumBeforePageBtnNeedToShow, boxEndNumAfterPageBtnNeedToShow, boxStartNum, boxEndNum, page){
		var html = '';
		
		html += '<form class="flex flex-jc-c" onsubmit="replyPage__submit(this); return false;" action="getReplies" method="POST">';
		html += '<c:if test="${totalPages > 1}">';
		html += '<input type="hidden" name="page" value="2">';
		html += '<li class="before-btn"><button type="submit" class="flex flex-ai-c">&lt;&lt; </button></li>';
		html += '</c:if>';  
		  
		
		if (boxStartNumBeforePageBtnNeedToShow) {
			html += '<c:if test="${boxStartNumBeforePageBtnNeedToShow}">';
			html += '<c:set var="aUrl" value="?id=${param.id}&page=${boxStartNumBeforePage}" />';
			html += '<li class="before-btn"><a href="${aUrl}" class="flex flex-ai-c"> &lt; </a></li>';
			html += '</c:if>';  
	
		}

		for (var i = boxStartNum; i <= boxEndNum; i++) {
			var selectedPageNum = "";
			if (i == page) {
				selectedPageNum = "article-page-menu__link--selected";
			}

			html += '<c:forEach var="i" begin="${boxStartNum}" end="${boxEndNum}" step="1">';
			html += '<c:set var="aClass" value="${page == i ? \'reply-page-menu__link--selected\' : \'???\' }" />';
			html += '<c:set var="aUrl" value="?id=${param.id}&page=${i}" />';
			html += '<li><a href="${aUrl}" class="page-btn flex flex-ai-c ${aClass}">${i}</a></li>'; 
			html += '</c:forEach>';  

		}
		if (boxEndNumAfterPageBtnNeedToShow) {

			html += '<c:if test="${boxEndNumAfterPageBtnNeedToShow}">';
			html += '<c:set var="aUrl" value="?id=${param.id}&page=${boxEndNumAfterPage}" />';
			html += '<li class="after-btn"><a href="${aUrl}" class="flex flex-ai-c"> &gt;</a></li>';  
			html += '</c:if>';  

		} 

		html += '<c:if test="${totalPages > 1}">';
		html += '<c:set var="aUrl" value="?page=${totalPages}&id=${param.id}" />';
		html += '<li class="after-btn"><a href="${aUrl}" class="flex flex-ai-c"> &gt;&gt;</a></li>';
		html += '</c:if>';  
		html += '</form>';

		ArticleReplyList__$replyPageBtnBox.append(html);
	}

	
	ArticleReplyList__loadMore();
</script>

 

<댓글 리스팅 java>

public String getReplies(HttpServletRequest request, HttpServletResponse response) {
		/* 상세페이지 댓글리스트 가져오기 시작 */
		// List<Reply> replies = articleService.getArticleReplies(id);

		int articleId = Util.getAsInt(request.getParameter("articleId"), 0);
		if (articleId == 0) {
			return msgAndBack(request, "게시물 번호를 입력하세요.");
		}
		
		int lastLoadedId = Util.getAsInt(request.getParameter("lastLoadedId"), 0);

		Member loginedMember = (Member) request.getAttribute("loginedMember");
		
		String relTypeCode = "article";

		// 총 댓글 수 카운트
		int totalCount = articleService.getRepliesCountByArticleId(articleId, relTypeCode);

		// 페이징
		int repliesInAPage = 5;
		// 한 페이지에 들어갈 article 수 설정
		int page = Util.getAsInt(request.getParameter("page"), 1);
		System.out.println(request.getParameter("page"));
		// pageNum이 null이면 1로 변환,정수형(int)이 아니면 정수형으로 변환

		List<Reply> replies = articleService.getRepliesForPrintByArticleId2(articleId, relTypeCode, loginedMember, lastLoadedId);

		int pageMenuBoxSize = 3; // 한 메인페이지 화면에 나올 하단 페이지 메뉴 버튼 수 ex) 1 2 3 4 5 6 7 8 9 10
		int totalRepliesCount = totalCount; // 전체 article의 수 카운팅
		int totalPages = (int) Math.ceil((double) totalRepliesCount / repliesInAPage); // 총 필요 페이지수 카운팅

		// 총 필요 페이지 수까지 버튼 만들기
		// 하단 페이지 이동 버튼 메뉴 만들기
		// 1. pageMenuBox내 시작 번호, 끝 번호 설정

		int previousPageNumCount = (page - 1) / pageMenuBoxSize; // 현재 페이지가 2이면 previousPageNumCount = 1/5
		int boxStartNum = pageMenuBoxSize * previousPageNumCount + 1; // 총 페이지 수 30이면 1~5 6~10 11~15
		int boxEndNum = pageMenuBoxSize + boxStartNum - 1;

		if (boxEndNum > totalPages) {
			boxEndNum = totalPages;
		}

		// 2. '이전','다음' 버튼 페이지 계산
		int boxStartNumBeforePage = boxStartNum - 1;
		if (boxStartNumBeforePage < 1) {
			boxStartNumBeforePage = 1;
		}
		int boxEndNumAfterPage = boxEndNum + 1;
		if (boxEndNumAfterPage > totalPages) {
			boxEndNumAfterPage = totalPages;
		}

		// 3. '이전','다음' 버튼 필요 유무 판별
		boolean boxStartNumBeforePageBtnNeedToShow = boxStartNumBeforePage != boxStartNum;
		boolean boxEndNumAfterPageBtnNeedToShow = boxEndNumAfterPage != boxEndNum;

		request.setAttribute("replies", replies);
		request.setAttribute("totalCount", totalCount);
		request.setAttribute("page", page);
		request.setAttribute("totalPages", totalPages);

		request.setAttribute("boxStartNum", boxStartNum);
		request.setAttribute("boxEndNum", boxEndNum);
		request.setAttribute("boxStartNumBeforePage", boxStartNumBeforePage);
		request.setAttribute("boxEndNumAfterPage", boxEndNumAfterPage);
		request.setAttribute("boxStartNumBeforePageBtnNeedToShow", boxStartNumBeforePageBtnNeedToShow);
		request.setAttribute("boxEndNumAfterPageBtnNeedToShow", boxEndNumAfterPageBtnNeedToShow);
		
		
		
		/* 상세페이지 댓글리스트 가져오기 끝 */
		String msg = "댓글 리스트 가져오기 완료";
		String code = "S-1";
		return jsonWithData(request, new ResultData(code, msg,"replies", replies,"totalCount",totalCount,"page",page));
	}