앞의 과정을 이상없이 진행했다. 이미 Ajax 처리까지는 완료되는 것을 확인했다.
남은 작업은 화면에서 버튼 등에서 발생하는 이벤트를 감지하고 Ajax호출의 결과를 화면에 반영하는 것이 남았다.
요구사항
1. 조회페이지가 열리면 댓글을 가져온다.
2. 댓글은 원글 아래쪽에 배치한다.
3. 댓글에 대한 처리는 모달창으로 처리한다.
댓글 목록 처리
댓글 목록을 위해서 별도의 <div>태그를 생성한다.
게시글과 관련된 화면 아래쪽에 추가한다.
<div class='row'>
<div class="col-lg-12">
<!-- /.panel -->
<div class="panel panel-default">
<!-- <div class="panel-heading">
<i class="fa fa-comments fa-fw"></i> Reply
</div> -->
<div class="panel-heading">
<i class="fa fa-comments fa-fw"></i> Reply
<button id='addReplyBtn' class='btn btn-primary btn-xs pull-right'>New
Reply</button>
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<ul class="chat">
</ul>
<!-- ./ end ul -->
</div>
<!-- /.panel .chat-panel -->
<div class="panel-footer"></div>
</div>
</div>
<!-- ./ end row -->
</div>
<div>안에는 나중에 댓글들을 위치시켜야하니 대략적인 위치를 잡는 식으로 작성한다.
그럼 위와같이 나타난다.
댓글의 목록은 <ul>태그 내에 <li> 태그를 이용해서 처리할 것이다.
각 <li>태그는 하나의 댓글을 의미하므로 수정이나 삭제시 이를 클릭하게 되고 그 를 위한 정보들을 넘겨줄 객체? 태그? 가 될것이다.
<ul class="chat">
<div class="header">
<strong>여기에 작성자</strong> <small class="pull-rigth text-mute">2021-10-08
13:00</small>
</div>
<p>여기에 댓글 내용이 들어간다!!</p>
</ul>
<ul>태그내에 간단하게 내용을 채워넣어주고~~
실행을 했더니 댓글의 모습을 제법 갖춘 형식으로 생성되었다.
앞으로 이런식으로 남겨질 것이라는것을 대략적으로 보여주는 예이다.
이벤트 처리
게시글 조회 페이지가 열리면 자동으로 댓글 목록을 가져와서 <li>태그를 구성해야한다.
이에 대한 처리는 $(doucument).ready()내에서 이루어 지도록 한다.
$(document).ready(function() {
console.log("hello");
var bnoValue = '<c:out value ="${board.bno}"/>';
var replyUL = $(".chat");
showList(1);
console.log(bnoValue);
function showList(page){
console.log("show list : " + page);
replyService.getList({bno:bnoValue,page: page|| 1 }, function(list) {
var str="";
if(list == null || list.length == 0){
console.log("댓글이없습니다.");
replyUL.html("");
return;
}
for (var i = 0, len = list.length || 0; i < len; i++) {
console.log("list : "+list[i].rno);
str +="<li class='left clearfix' data-rno='"+list[i].rno+"'>";
str +=" <div><div class='header'><strong class='primary-font'>"+list[i].replyer+"</strong>";
str +=" <small class='pull-right text-muted'>"+replyService.displayTime(list[i].replyDate)+"</small></div>";
str +=" <p>"+list[i].reply+"</p></div></li>";
}
replyUL.html(str);
});//end function
}
});
로그는 좀많이 찍어놨다. 처음해보는거라
시간처리이다. XML이나 JSON형태로 데이터를 받을 때는 순수하게 숫자로 표현되는 시간 값이 나오게 되어있다.
그런데 최근 웹페이지들은 해당일에 해당하는 데이터는 시/분/초
전일 또는 과거글은 년/월/시 로 나온다
그것은 현재일 - 전일 = 24시간 전인가? 이런 방식을 이용해서 만들어보고 화면에 출력하도록 해보자
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)) {
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('');
} else {
var yy = dateObj.getFullYear();
var mm = dateObj.getMonth() + 1; // getMonth() is zero-based
var dd = dateObj.getDate();
return [ yy, '/', (mm > 9 ? '' : '0') + mm, '/',
(dd > 9 ? '' : '0') + dd ].join('');
}
}
;
displayTime()은 Ajax에서 데이터를 가져와서 html을 만들어주는 부분
replyService.displayTime(list[i].replyDate)
형태로 적용하도록하자
즉, 지금한 작업들은 DB에서 날짜 데이터를 가져와서
지금 날짜, 그리고 해당 DB의 날짜 를 뺀다. = gap
그런데 이 gap이 24시간이 안되었다면 ?! ( 1000밀리초 * 60 * 60 * 24 ) 전이라면 ?!
-> [ (hh > 9 ? '' : '0') + hh, ':', (mi > 9 ? '' : '0') + mi,
':', (ss > 9 ? '' : '0') + ss ] = 시:분:초 로 나타내라
그게 아니면
-> [ yy, '/', (mm > 9 ? '' : '0') + mm, '/',
(dd > 9 ? '' : '0') + dd ]
년/월/일 로 나타내라
이런 의미다. 한번 따라 작성하면 어렵지 않은 수식이다.
마찬가지로 displayTime : displayTime 을 잊지말자 - 리턴에
그리고 get.jsp 파일의 댓글들이 나타나는 부분을 수정하자
http://localhost:8080/board/get?bno=1 를 이용해서 결과 값을 보겠다.
로그들이 찍힌걸 알수있다. - 이후확인되었으면 쓸데없는 로그는 삭제해주자
showList()는 페이지 번호를 파라미터로 받도록 설계했고, 만일 파라미터가 없는 경우 자동으로 1페이작 되도록 설정했다. ( || 또는 을 이용해서) 브라우저 DOM처리가 끝나면 자동으로 showList()가 호출된다.
그러면서 <ul>태그 내에 내용이 반복문으로 추가되어 리스트가 나온다.
+테스트를 위해 하드코딩되었던 것은 지워주자~
<li class="left clearfix" data-rno='12'>
<div class="header">
<strong>여기에 작성자</strong> <small class="pull-rigth text-mute">2021-10-08
13:00</small>
</div>
<p>여기에 댓글 내용이 들어간다!!</p>
</li>
이걸 말하는것이다
새로운 댓글 처리
댓글의 추가는 모달창을 이용해서 진행시키자. 모달창은 별도로 화면 중앙에 위치한다.
<script> 태그가 시작하기 직전에 모달을 넣어주는데 주석을 넣어 어느정도 구분이 되게 만들어주자
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">REPLY MODAL</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label>Reply</label>
<input class="form-control" name='reply' value='New Reply!!!!'>
</div>
<div class="form-group">
<label>Replyer</label>
<input class="form-control" name='replyer' value='replyer'>
</div>
<div class="form-group">
<label>Reply Date</label>
<input class="form-control" name='replyDate' value='2018-01-01 13:13'>
</div>
</div>
<div class="modal-footer">
<button id='modalModBtn' type="button" class="btn btn-warning">Modify</button>
<button id='modalRemoveBtn' type="button" class="btn btn-danger">Remove</button>
<button id='modalRegisterBtn' type="button" class="btn btn-primary">Register</button>
<button id='modalCloseBtn' type="button" class="btn btn-default">Close</button>
</div> </div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
모달창은 브라우저에서 댓글에 대한 여러 작업에서 활용할 것이므로 필요한 모든 내용을 담아내었다.
그리고 각작업에 맞게 버튼이나 입력창이 보이거나 감춰지도록 한다.
새로운 댓글의 추가 버튼 이벤트 처리
댓글의 상단 New Reply를 클릭하면 화면에서는 모달창을 아래와 같이 보이게 처리된다.
버튼을 눌렀을때 모달창이 나오도록 처리하자
댓글이 나오도록 처리하는 스크립트 바로 밑에 추가하자
<script type="text/javascript">
$(document).ready(
...생략...
var modal = $(".modal");
var modalInputReply = modal.find("input[name='reply']");
var modalInputReplyer = modal.find("input[name='replyer']");
var modalInputReplyDate = modal.find("input[name='replyDate']");
var modalModBtn = $("#modalModBtn");
var modalRemoveBtn = $("#modalRemoveBtn");
var modalRegisterBtn = $("#modalRegisterBtn");
$("#addReplyBtn").on("click",function(e){
modal.find("input").val("");
modalInputReplyDate.closest("div").hide();
modal.find("button[id!='modalCloseBtn']").hide();
modalRegisterBtn.show();
$(".modal").modal("show");
});
});
</script>
내가 이제 버튼을 클릭하면 입력할 수 있는 모달창을 볼 수 있따.
댓글 등록 및 목록 갱신
새로운 댓글의 추가는 필요한 댓글의 내용과 댓글의 작성자 항목만으로 추가해서 모달창 아래쪽의 등록 버튼을 클릭해서 처리되게한다.
그럼 스크립트에 해당 버튼에 기능을 걸어주자
modalRegisterBtn.on("click",function(e){
var reply = {
reply: modalInputReply.val(),
replyer:modalInputReplyer.val(),
bno:bnoValue
};
replyService.add(reply, function(result){
alert(result);
modal.find("input").val("");
modal.modal("hide");
//showList(1);
showList(-1);
});
js 파일에있는 add매서드를 불르고 거기에 reply(내용, 작성자, 글번호)를 넘긴다.
댓글이 정상적으로 추가되면 경고창을 이용해 성공했다는 사실을 알려주고 등록한 내용으로 다시 등록할 수 없도록 입력항목을 비우고 모달창을 닫아준다.
모달창에 글을 썼다. 글내용 모두 확인했고
네이버 웨일전용 경고창이 떳다 성공했다고 한다.
콘솔창에 찍인 로그들도 정상적으로 추가가 되었고
맨밑 화이팅! 이라는 작성자 명으로 글이 올라왔을 볼 수 있다.
그런데 이과정중 F5를 눌러 갱신을 하였다....
이런 문제 때문에 댓글을 추가한 후에는 다시 댓글의 목록을 갱신할 필요가 있다.
modalRegisterBtn.on("click", function(e) {
var reply = {
reply : modalInputReply.val(),
replyer : modalInputReplyer.val(),
bno : bnoValue
};
replyService.add(reply, function(result) {
alert(result);
modal.find("input").val("");
modal.modal("hide");
showList(1);
});
});
맨 밑에 showList(1)을 추가하여 댓글이 추가된 후 그 사이에 추가되었을지 모르는 새로운 댓글도 가져오게했다.
특정 댓글의 클릭 이벤트 처리
댓글은 댓글의 목록에서 모두 출력된다. 그리고 그것들을 수정, 삭제키위해서는 원칙적으로 로그인 된 사용자가 해당 댓글의 작성자인 경우에만 허락 되어야 한다.
그런데 지금 로그인을 구현안했으니 우선적으로 어떤 댓글이든간에 수정/삭제가 되도록해보자
DOM내에서 이벤트 리스너를 등록하는 것은 반드시 해당 DOM요소가 존재해야만 가능하다.
위와같은 동적으로 Ajax를 통해서 <li> 태그들이 만들어지면 이후에 이벤트를 등록해야한다.
이것을 이벤트위임(delegation) 의 형태로 작성해야한다.
이벤트위임이란 ? - 이벤트를 동적으로 생성되는 요소가 아닌 이미 존재하는 요소에 이벤트를 걸어주고, 나중에 이벤트의 대상을 변경해주는 방식
jQuery는 on()을 이용해서 쉽게 처리가능하다.
$(".chat").on("click", "li", function(e) {
var rno = $(this).data("rno");
console.log(rno);
});
jQuery에서 이벤트를 위임하는 방식은 이미 존재하는 DOM의 요소에 이벤트를 처리하고 나중에 동적으로 생기는
요소들에게 대해 파라미터 형식으로 지정한다.
위의 경우 <ul>태그의 클래스 'chat' 을 이용해서 이벤트를 걸고 실제 이벤트의 대상은 <li>태그가 되도록하자.
댓글들을 클릭했을때 우측 하단에 파랑색 콘솔이 보인다. 12번, 15번, 17번, 그리고 12번은 2번눌러서 동그라미 안에 2가있다.
이제 이벤트를 등록해주자
$(".chat").on("click", "li", function(e){
var rno = $(this).data("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);
modal.find("button[id !='modalCloseBtn']").hide();
modalModBtn.show();
modalRemoveBtn.show();
$(".modal").modal("show");
});
});
댓글 조회하는것은 모든 내용이 화면에 있기 때문에 별도로 조회할 필요는 없다.
그런데 원칙적으로(??) Ajax로 댓글을 조회한 후 수정/삭제를 하는것이 정상이니까
댓글을 가져온 후에는 필요한 항목들을 채우고 수정과 삭제에 필요한 댓글 번호속성도 만들어 추가해 두자,
보이는 사진과 같이 뜬다. 이내용은
http://localhost:8080/replies/7 로 들어갔을때 나오는 내용과 일치한다.
댓글 수정/삭제 처리
댓글의 삭제는 가장 간단하게 결과를 보여주는 작업만을 처리하면 된다.
즉 가장 간단하게 처리가능하다. 댓글넘버만 넘겨주면 되니까
jsp내 에서 삭제하는 기능을 추가하자
modalRemoveBtn.on("click", function (e){
var rno = modal.data("rno");
replyService.remove(rno, function(result){
alert(result);
modal.modal("hide");
showList(1);
});
});
modalModBtn.on("click", function(e){
var reply = {rno:modal.data("rno"), reply: modalInputReply.val()};
replyService.update(reply, function(result){
alert(result);
modal.modal("hide");
showList(1);
});
});
이로써 댓글장의 CRUD기능을 모두 구현해보았다.
로그인 유무에 따른 변화라던가 삭제/수정할 수 있는 권한 등은 아직 남았지만
Ajax를 공부할 수 있는 소중한 시간이었다.
다음엔 댓글 페이징을 할 것이다.
'Spring공부 > 1-REST' 카테고리의 다른 글
REST방식(9)-댓글페이징처리 (0) | 2021.10.11 |
---|---|
REST방식(8)-댓글페이징처리 (0) | 2021.10.11 |
REST방식(8)-Ajax (0) | 2021.10.08 |
REST방식(7)-Ajax댓글처리 (2) | 2021.10.07 |
REST방식(6)-Ajax댓글처리 (2) | 2021.10.07 |
댓글