-
11주차 일 1029 진행도광주인력개발원 일일포스팅(메모장) 2023. 10. 29. 18:19728x90반응형
오늘 까지 프로젝트를 정리해서 팀원과 합치고 해야하는데
초반 계획했던 것들을 대부분 구현해내지 못해 아쉬움이 큰 상태이다.지금까지 구현해낸 것들을 다듬어 퀄리티를 높여야겠다.
어제 오늘 구현한 것은 댓글(내림차순), 수정, 삭제이다.
타임리프를 이용중인데
이상하게 버튼에 comment id 값이 안나와서
(나중에 방법을 찾아봐야겠다)
각 요소에 class를 줘서 for문을 돌려 값을 가져왔다.
plan.html
<!DOCTYPE html><html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><link rel="stylesheet" th:href="@{/cssjs/planDetail.css}" /><title>PDetail</title></head>
<body><header class="gnbCommon" style="height: 90px;"><div class="gnb"><h1 class="logo"><a href="/"><img src="/img/logo.png" alt="Travel"></a></h1></div><div class="menu"><div class="depth"><div class="swiper-container"><ul class="swiper-wrapper"><li><a href="">홈</a></li><li><a href="">테마</a></li><li><a href="">지역</a></li><li><a href="">여행콕콕</a></li><li><a href="">여행상품 홍보관</a></li><li><a href="">여행정보</a></li><li><a href="">여행지도</a></li></ul></div></div></div><div class="form"><span class="input"><input type="text" placeholder="어떤 여행?"><a href="" class="search">검색</a></span></div></header><div id="content"><div class="title1"><div><h2 id="topTitle" name="title" th:text="${travelPlan.title}"></h2></div><div class="write_date"><span name="planDate" th:text="${#temporals.format(travelPlan.planDate, 'yy년 mm월 dd일')}"></span><br><span name="name" th:text="${travelPlan.member.name}"></span></div><div class="post_area"><button type="button" class="btn_good" id="likeButton"><span class="ico">좋아요</span><span class="num" id="conLike"></span></button><span class="num_view"><em class="tit">조회수</em><span class="num" id="conRead">[[${#lists.size(travelPlan.views)}]]</span></span></div></div><div class="cont_detail"><div class="content"><p th:utext="${travelPlan.content}"></p></div><div class="tok"><div class="tokwrap"><h3 class="tit">댓글<span></span></h3><div class="write"><div class="tokform"></div><form name="tform" id="tform"><label class="blind" for="comment">로그인 후 소중한 댓글을 남기시오.</label><span class="writeform" style="height: 80px;"><textarea name="comment" id="textareaId" cols="30" rows="10"placeholder="로그인 후 소중한 댓글을 남기시오." style="height: 80px;"></textarea></span><div class="push"><button id="submitButton" class="tenter" type="button" onclick="tenter()">입력</button></div></form></div><div class="reply"><div class="list_reply"><ul th:each="comment : ${commentList}"><li id="area"><div class="profile"><div class="photo"></div></div><div class="date"><em class="name" th:text="${comment.member.name}"></em><span class="reply_date"th:text="${#temporals.format(comment.commentTime, 'yy년 mm월 dd일')}"></span><div class="txt"><p id="commContent" th:text="${comment.content}"></p></div></div><div class="active"><div><input type="hidden" class="memberId" th:value="${comment.member.id}"><input type="hidden" class="cid" th:if="${comment.id != null}"th:value="${comment.id}"><button type="button" class="delete" th:if="${#session.getAttribute('id') == comment.member.id}" >삭제</button><button type="button"th:if="${#session.getAttribute('id') == comment.member.id}" id="modify" class="modify">수정</button></div><div style="display: none;" id="editInput" class="mBox"><input type="text" id="editComment" class="editComment"placeholder="댓글을 수정하세요"><div class="mbtn"><button type="button" class="mbutton" id="editButton">완료</button></div></div></div></li></ul><div class="commentMore"><a href="javascript:void(0);" class="btn_more" id="loadMoreComments">댓글 더보기</a></div><div class="footer"><p>Kepco Boot Capm</p></div></div></div></div></div></div><input type="hidden" id="memberid" th:if="${session.id != null}" th:value="${session.id}"><input type="hidden" id="planid" th:if="${travelPlan.id != null}" th:value="${travelPlan.id}"></div></body>
<script>var memberId = document.getElementById("memberid");var planid = document.getElementById("planid");var planId = planid.value;var likeButton = document.getElementById("likeButton");
const num = document.querySelector('#conLike');
var param = { memberId: memberId.value, planId: planId };
var comment = document.getElementById("textareaId");var replyId = document.getElementById("modify");var reply = { memberId: memberId.value, planId: planId, comment1: comment.value }
async function checkLike() {try {const response = await fetch('/pcheckLike', {method: 'POST',headers: {'Content-Type': 'application/json'},body: JSON.stringify(param)});
if (response.ok) {const data = await response.json();console.log(data);if (data.status) {likeButton.classList.add('active');} else {likeButton.classList.remove('active');}num.innerText = data.like;} else {console.error('Error:', response.status, response.statusText);}} catch (error) {console.error(error);}}
checkLike();const conLike = document.getElementById("conLike");likeButton.addEventListener("click", async function () {try {const response = await fetch('/pbtnlike', {method: 'POST',headers: {'Content-Type': 'application/json'},body: JSON.stringify(param)
});
if (response.ok) {const data = await response.json();alert(data.msg);if (data.result) {checkLike();}} else {console.error('Error:', response.status, response.statusText);}} catch (error) {console.error(error);}});
async function tenter() {if (comment.value === "") {alert("댓글 내용을 입력하세요.");return;}
try {const requestBody = {memberId: memberId.value,planId: planid.value,comment: comment.value,replyId: null};
const response = await sendCommentRequest("/pComment", requestBody);
if (response.ok) {const result = await response.json();if (result.result) {alert(result.msg);window.location.reload();} else {alert("댓글 저장 실패: " + result.msg);}} else {alert("서버 오류로 댓글을 저장할 수 없습니다.");}} catch (error) {console.error("댓글 저장 중 오류 발생:", error);}}
async function sendCommentRequest(url, data) {const response = await fetch(url, {method: "POST",headers: {"Content-Type": "application/json",},body: JSON.stringify(data),});
if (!response.ok) {throw new Error("서버 응답에 문제가 있습니다.");}
return response;}
////수정modifyButton = document.querySelectorAll('.modify');
for (let i = 0; i < modifyButton.length; i++) {modifyButton.item(i).addEventListener("click", () => {
document.querySelectorAll('.mBox').item(i).style.display = "block";})
}function editReply(button) {var editInput = document.getElementById("editInput");editInput.style.display = "block";}
let mbutton = document.querySelectorAll(".mbutton");let cid = document.querySelectorAll('.cid');let newComment = document.querySelectorAll('.editComment');let userId = document.querySelectorAll('.memberId');
for (let i = 0; i < mbutton.length; i++) {
mbutton.item(i).addEventListener("click", () => {
fetch('/pComment', {method: 'POST',headers: {'Content-Type': 'application/json'},body: JSON.stringify({ replyId: cid.item(i).value, newComment: newComment.item(i).value, memberId: userId.item(i).value, planId, planId })}).then(response => response.json()).then(data => {if (data.result) {alert(data.msg);window.location.reload();} else {alert(data.msg);}}).catch(error => {console.error('에러:', error);});var editInput = document.getElementById("editInput");editInput.style.display = "none";
})}/////// 삭제
const dtnD = document.querySelectorAll(".delete");
for (let i = 0; i< dtnD.length;i++){
dtnD.item(i).addEventListener("click",()=>{fetch('/pdelete' , {method: 'POST',headers: {'Content-Type': 'application/json'},body: JSON.stringify({ replyId: cid.item(i).value, memberId: userId.item(i).value})}).then(response => response.json()).then(data => {if (data.result) {alert(data.msg);window.location.reload();} else {alert(data.msg);}}).catch(function (error) {console.error("에러:", error);});})}</script>
</html>댓글, 수정 Controller
@ResponseBody@PostMapping("/pComment")public Map<String, Object> pCommentPost(@RequestBody Map<String, String> commentMap, Model model) {Map<String, Object> map = new HashMap<>();try {Integer memberId = parseInt(commentMap.get("memberId"));Integer planId = parseInt(commentMap.get("planId"));String content = commentMap.get("comment");String replyId = commentMap.get("replyId");String editedComment = commentMap.get("newComment");
if (memberId == null) {map.put("msg", "로그인 후 이용해주세요.");map.put("result", false);} else if (replyId != null) {Comment findComment = commentRepository.findById(parseInt(replyId)).orElse(null);
if (findComment != null && findComment.getMember().getId().equals(memberId) && editedComment != null) {findComment.setContent(editedComment);commentRepository.save(findComment);map.put("msg", "댓글을 수정했습니다.");map.put("result", true);} else {map.put("msg", "댓글을 확인할 수 없습니다.");map.put("result", false);}} else if (content != null) {Comment comment = new Comment();Member member = new Member();TravelPlan plan = new TravelPlan();
comment.setContent(content);
member.setId(memberId);comment.setMember(member);
plan.setId(planId);comment.setTravelPlan(plan);
commentRepository.save(comment);map.put("msg", "댓글을 작성했습니다.");map.put("result", true);} else {map.put("msg", "내용을 입력해주세요.");map.put("result", false);}} catch (NumberFormatException e) {map.put("status", false);map.put("statustext", "댓글에 오류가 발생했습니다.");}return map;}삭제 Controller
@PostMapping("/pdelete")@ResponseBodypublic Map<String, Object> pdeleteComment(@RequestBody Map<String, String> commentDelete) {Map<String, Object> map = new HashMap<>();try {Integer replyId = Integer.parseInt(commentDelete.get("replyId"));Integer memberId = Integer.parseInt(commentDelete.get("memberId"));
if (memberId == null) {map.put("msg", "로그인 후 이용해주세요.");map.put("result", false);} else {Optional<Comment> commentOptional = commentRepository.findById(replyId);if (commentOptional.isPresent()) {Comment comment = commentOptional.get();if (comment.getMember().getId() == memberId) {commentRepository.delete(comment);map.put("msg", "댓글이 삭제되었습니다.");map.put("result", true);} else {map.put("msg", "댓글 삭제에 실패하였습니다.");map.put("result", false);}} else {map.put("msg", "댓글을 찾을 수 없습니다.");map.put("result", false);}}} catch (NumberFormatException e) {map.put("msg", "올바른 숫자 형식이 아닙니다.");map.put("result", false);}return map;}허허... 요상한 코드로다..
허점이 많지만 할게 많다는 핑계로 넘어가겠숨다..
그럼 20000728x90반응형'광주인력개발원 일일포스팅(메모장)' 카테고리의 다른 글
11주차 수 1101 (0) 2023.11.01 11주자 월 1030 프로젝트 끝 (5) 2023.10.30 10주차 금 1027 진행도 (3) 2023.10.27 10주차 목 1026 진행도 (0) 2023.10.26 10주차 화 1024 진행도 (0) 2023.10.24