danDevlog

Spring - 12 (댓글 기능 -3 View) 본문

Spring 게시판 만들기

Spring - 12 (댓글 기능 -3 View)

단데기이 2022. 4. 25. 17:00
728x90

콘솔에 출력되는것을 확인하였으니 이제 게시물에서 볼 수 있도록 만들어준다.

 

get.jsp 스크립트 부분에 추가해준다.

		var replyUL = $(".chat");
		
		function showList(page){
			replyService.getList(
					{
						bno : bnoValue,
						page : page || 1
					},
					// 익명함수 : 이름이 없으며 즉시 실행
					function(list) {
						var str = "";
						
						if (list ==null || list.length == 0 ){
							replyUL.html("");
							return;
						} // 목록이 없을때 처리 끝.
						
						for (var i = 0, len = list.length || 0; i<len; i++){
							str += "<li class='left ";
							str += "clearfix' data-rno='";
							str += list[i].rno+"'>";
							str += "<div><div class='header' ";
							str += "><strong class='";
							str += "primart-font'>";
							str += list[i].replyer+ "</strong>";
							str += "<small class='float-sm-right '>";
							str += list[i].replyDate
							+ "</small></div>";
							str += "<p>" + list[i].reply;
							str += "</p></div></li>";
						}
						replyUL.html(str); 
					}); // end
		} // end_showlist
		showList(1);
		// 덧글 목록 표시 끝

replyService파일에서 getList 함수를 부른다. 

페이지 번호를 파라미터로 받도록 설계하고, 만일 파라미터가 없는 경우에는 자동으로  1페이지가 되도록 설정한다.

브라우저에서 DOM처리가 끝나면 자동으로 showList()가 호출되면서 <ul> 태그 내에 내용으로 처리된다.

만일 1페이지가 아닌 경우라면 기존 <ul>에 <li>들이 추가되는 형태이다.

 

잘 출력되지만 오른쪽 시간 부분을 보면 우리가 읽을 수 있는 시간 형태로 나오지 않는다.

댓글을 작성한지 24시간 이내이면 작성 시간만 표시, 24시간 이후라면 날짜까지 출력되게 만들어준다.

 

해당 부분은 reply.js 에서 코드를 수정한다.

        function displayTime(timeValue){
            var today = new Date(); // 현재 시간
            var gap = today.getTime() - timeValue;
            // 시간차이 연산.
            var dateObj = new Date(timeValue);
            // 덧글이 등록된 시간을 변수에 할당.
            var str = "";
            
            if(gap<(1000*60*60*24)){
                // 시간차이가 24시간 미만이 라면,
                var hh = dateObj.getHours();
                var mi = dateObj.getMinutes();
                var ss = dateObj.getSeconds();
                
                return [ (hh>9?'':'0')+hh, ':'
             ,(mi>9?'':'0')+mi
             ,':',(ss>9?'':'0')+ss].join('');
 
                // 배열 요소를 문자열로 변환. join
                // 시간에 포맷을 맞추기 위해서
                // 0~9 까지는 앞에 0을 추가 표시.
            }else{
                var yy = dateObj.getFullYear();
                var mm = dateObj.getMonth()+1;
                var dd = dateObj.getDate();
                
                return [yy, '/', (mm>9?'':'0')+mm, '/',
                    (dd>9?'':'0')+dd].join('');
            }
        }

today 변수에 현재 시간을 담고, gap이란 변수에 현재 시간과 댓글 작성 시간의 차이를 연산한다.

return 부분을 해석하면 시,분,초 에서 시 부분이 9가 넘어가면 공백, 아니라면 0을 붙여서

01시, 02시, 03시......09시 처럼 앞에 0을 붙여준다. 분과 초도 마찬가지이다.

 

get.jsp 에서 임시로 시간 출력하는 부분의 코드를 수정한다.

for (var i = 0, len = list.length || 0; i<len; i++){
	str += "<li class='left ";
	str += "clearfix' data-rno='";
	str += list[i].rno+"'>";
	str += "<div><div class='header' ";
	str += "><strong class='";
	str += "primart-font'>";
	str += list[i].replyer+ "</strong>";
	str += "<small class='float-sm-right '>";
	str += replyService.displayTime(list[i].replyDate)
		+ "</small></div>";
	str += "<p>" + list[i].reply;
	str += "</p></div></li>";
}
replyUL.html(str);
str += replyService.displayTime(list[i].replyDate)
		+ "</small></div>";

replyService에서 displayTime 함수를 호출해서 시간 형식을 변경해준다.

 

지금 까지는 새로고침을 해줘야 댓글을 작성한것이 반영되었는데, 이제 새로고침 없이 바로 반영되게 변경한다.

get.jsp의 덧글 쓰기 스크립트 기능 부분에  showList(-1); 을 추가해준다.

// 모달창에서 덧글 쓰기
		modalRegisterBtn.on("click", function(e) {
			// 덧글 등록 버튼을 눌렀다면,
			var reply = {
				reply : modalInputReply.val(),
				replyer : modalInputReplyer.val(),
				bno : bnoValue
			}; // ajax로 전달할 reply 객체 선언 및 할당.
			replyService.add(reply, function(result) {
				alert(result);
				// ajax 처리후 결과 리턴.
				modal.find("input").val("");
				// 모달창 초기화
				modal.modal("hide"); // 모달창 숨기기
				
				// 덧글 작성 즉시 목록 갱신용 함수 호출.
				showList(-1);
				// -1 이나 99나 현재는 영향이 없지만 차후 덧글의 페이징 처리에서 -1 사용 예정
				
				
			});
		}); // 덧글 쓰기버튼처리 끝.

 

한 개의 덧글을 읽는 기능창을 만들어준다.

reply.js

        function get(rno, callback, error){
            $.get("/replies/" + rno, function(result){
                if(callback){
                    callback(result);
                }
            }).fail(function(xhr, status, er){
                if(error){
                    error(er);
                }
            });
        }
return {
            add: add,
            getList: getList,
            displayTime : displayTime,
            get: get,
         }; // 변수명.호출명 예) replyService.add
  })(); // 즉시 실행 함수: 명시하는 것과 동시에 메모리에 등록.

 

get.jsp

모달의 수정과 삭제 버튼 요소를 지정해준다.

		var modalModBtn=$("#modalModBtn");
		var modalRemoveBtn = $("#modalRemoveBtn");
		// 댓글 정보 확인
        $(".chat").on("click", "li", function(e){
            // 클래스 char 을 클릭하는데, 하위 요소가 li라면,
            var rno = $(this).data("rno");
            // 덧글에 포함된 값들 중에서 rno를 추출하여 변수 할당.
            console.log(rno);
            
            replyService.get(rno,function(reply){
                modalInputReply.val(reply.reply);
                modalInputReplyer.val(reply.replyer);
                modalInputReplyDate.val(replyService.displayTime(reply.replyDate))
                        .attr("readonly", "readonly");
                // 댓글 목록의 값들을 모달창에 할당.
                modal.data("rno", reply.rno);
                // 표시되는 모달창에 rno 라는 이름으로 data-rno를 저장.
                modal.find("button[id != 'modalCloseBtn']").hide();
                modalModBtn.show();
                modalRemoveBtn.show();
                // 버튼 보이기 설정.
                $("#myModal").modal("show");
            }); // 끝_덧글 읽기.
        });

 

덧글 수정 처리 

reply.js

        function update(reply, callback, error){
            console.log("rno: " + reply.rno);
            $.ajax({
                type : 'put',
                url : '/replies/' + reply.rno,
                data : JSON.stringify(reply),
                contentType : "application/json;charset=utf-8",
                success : function(result, status, xhr) {
                    if(callback){
                        callback(result);
                    }
                }
            });
        }

get.jsp

		// 덧글 수정 처리 시작.
		modalModBtn.on("click", function(e) {
			var reply = {
					rno : modal.data("rno"),
					/* replyer : modalInputReplyer.val(), */
					reply : modalInputReply.val()
			};
			replyService.update(reply, function(result){
				alert(result);
				modal.modal("hide");
				showList(-1);
			});
		}); // 끝 덧글 수정.

 

댓글 삭제 처리

reply.js

        function remove(rno, callback, error){
        	$.ajax({
        		type : 'delete',
        		url : '/replies/' + rno,
        		success : function(deleteResult, status, xhr) {
        			if (callback) {
        				callback(deleteResult);
        			}
        		},
        		error : function(xhr, status, er) {
        			if (error){
        				error(er);
        			}
        		}
        	});
        }
         return {
            add: add,
            getList: getList,
            displayTime : displayTime,
            get: get,
            update: update,
            remove: remove
         }; // 변수명.호출명 예) replyService.add
  })(); // 즉시 실행 함수: 명시하는 것과 동시에 메모리에 등록.

get.jsp

		// 덧글 삭제 처리.
		modalRemoveBtn.on("click", function(e){
			var rno = modal.data("rno");
			replyService.remove(rno, function(result){
				alert(result);
				modal.modal("hide");
				showList(-1);
			});
		});

 

 

 

 

Comments