이번 시간은 댓글 추가,삭제 기능을 기반으로 포스팅하겠습니다.
Spring MVC 패턴에 맞게 정의한 소스 코드이며, 댓글 관련 소스코드 모두 첨부합니다.
comment.jsp
ajax, javascript, jquery 형식으로 댓글을 추가,수정,삭제 하는 방법입니다.
줄 바꿈의 핵심 로직에는 빨간색으로 표시 해두었으니, 참고하시기 바랍니다.
각 게시글 번호에 맞는 댓글의 갯수와 댓글을 출력해주기 위해 아래 소스 코드에서는 qnaInfo로 조회했습니다.
가장 간단한 방법으로 줄바꿈 기능을 사용해보고자 작성한 소스코드입니다.
원래는 댓글 기능만 추가하려고 했었는데, 질문답변 게시판도 댓글 형식으로 답변을 남겨보자! 하고 시작한 작업입니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 | <script type="text/javascript"> var bno = '${qnaInfo.bdNum}'; //게시글 번호 //댓글 목록 function commentList(){ var upCheck = ${loginInfo.memNum} $.ajax({ url : '/comment/list', type : 'get', data : {'bdNum':bno}, success : function(data){ var a =''; $.each(data, function(key, value){ if(upCheck == 1) { var contentV = value.cmtContent.replace(/(?:\r\n|\r|\n)/g, '<br>'); a += '<div class="commentArea" style="border-bottom:1px solid darkgray; margin-bottom: 15px;">'; a += '<div class="commentInfo'+value.cmtNum+'">'+' 작성자 : '+value.cmtWriter + '<a href="#" onclick="commentDelete('+value.cmtNum+');"> 삭제</a>' + '<a href="#" onclick="commentUpdate('+value.cmtNum+',\''+contentV+'\');"> 수정</a>'; a += '<p class="card-subtitle mb-2 text-muted"><small> (' + value.cmtWDate + ')</small></p>'; a += '</div>'; a += '<div class="commentContent'+value.cmtNum+'"> <p id="comp">'+value.cmtContent +'</p>'; a += '</div></div>'; } else { a += '<div class="commentArea" style="border-bottom:1px solid darkgray; margin-bottom: 15px;">'; a += '<div class="commentInfo'+value.cmtNum+'">'+' 작성자 : '+value.cmtWriter + '<p class="card-subtitle mb-2 text-muted"><small> (' + value.cmtWDate + ')</small></p>'; a += '<div class="commentContent'+value.cmtNum+'"> <p>'+value.cmtContent +'</p></div>'; a += '</div></div>'; } }); $(".commentList").html(a); // $("div[class=commentList]").html(a); } }); } //댓글 수정 - 댓글 내용 출력을 input 폼으로 변경 function commentUpdate(cmtNum, cmtContent){ var a =''; var contentV = cmtContent.split('<br>').join("\r\n"); var contentW = contentV.split('</a>').join(""); a += '<div class="input-group">'; //a += '<input type="text" class="form-control" name="cmtContent_'+cmtNum+'" value="'+cmtContent+'"/>'; a += '<textarea name="cmtContent_'+cmtNum+'" class="form-control" rows="4" cols="70" placeholder="내용을 입력하세요.">'+ contentW +'</textarea>'; a += '<span class="input-group-btn"><button class="btn btn-default" type="button" onclick="commentUpdateProc('+cmtNum+');">수정</button> </span>'; a += '</div>'; $('.commentContent'+cmtNum).html(a); } //댓글 수정 function commentUpdateProc(cmtNum){ var updateContent = $('textarea[name=cmtContent_'+cmtNum+']').val(); $.ajax({ url : '/comment/update', type : 'post', data : {'cmtContent' : updateContent, 'cmtNum' : cmtNum}, success : function(data){ if(data) commentList(cmtNum); //댓글 수정후 목록 출력 } }); } //댓글 삭제 function commentDelete(cmtNum){ $.ajax({ url : '/comment/delete/'+cmtNum, type : 'post', success : function(data){ if(data) commentList(cmtNum); //댓글 삭제후 목록 출력 } }); } $(document).ready(function() { $('button[name=insertCommentBtn]').click(function(){ //댓글 등록 버튼 클릭시 //alert("등록 버튼"); var insertData = $('form[name=insertCommentForm]').serialize(); //insertCommentForm의 내용을 가져옴 //alert(JSON.stringify(insertData)); commentInsert(insertData); //Insert 함수호출(아래) }); //댓글 등록 function commentInsert(insertData){ $.ajax({ url : '/comment/insertVisitor', type : 'post', data : insertData, success : function(data){ if(data) { commentList(); //댓글 작성 후 댓글 목록 reload $('#cmtContent').val(''); } } }); } commentList(); //페이지 로딩시 댓글 목록 출력 }); </script>
| cs |
CommentVo.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | package kr.or.infobee.comment.service; import org.apache.commons.lang3.builder.ToStringBuilder; public class CommentVo { private int cmtNum; private int bdNum; private String cmtWriter; private int memNum; private String cmtContent; private String cmtDel; private String cmtWDate; public int getCmtNum() { return cmtNum; } public void setCmtNum(int cmtNum) { this.cmtNum = cmtNum; } public int getBdNum() { return bdNum; } public void setBdNum(int bdNum) { this.bdNum = bdNum; } public String getCmtWriter() { return cmtWriter; } public void setCmtWriter(String cmtWriter) { this.cmtWriter = cmtWriter; } public int getEmpNum() { return memNum; } public void setEmpNum(int memNum) { this.memNum = memNum; } public String getCmtContent() { return cmtContent; } public void setCmtContent(String cmtContent) { this.cmtContent = cmtContent; } public String getCmtDel() { return cmtDel; } public void setCmtDel(String cmtDel) { this.cmtDel = cmtDel; } public String getCmtWDate() { return cmtWDate; } public void setCmtWDate(String cmtWDate) { this.cmtWDate = cmtWDate; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } } | cs |
CommentController.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 | package kr.or.infobee.comment.web; import java.util.HashMap; import java.util.List; import javax.servlet.http.Cookie; import javax.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import kr.or.infobee.comment.service.CommentService; import kr.or.infobee.comment.service.CommentVo; import kr.or.infobee.login.service.LoginVo; @Controller @RequestMapping(value = "/comment") public class CommentController { private final Logger log = LoggerFactory.getLogger(this.getClass()); @Autowired private CommentService commentService; @RequestMapping(value = "/list") public @ResponseBody List<CommentVo> getCommentList(Model model, @ModelAttribute CommentVo commentVo, HttpSession session) throws Exception { session.getAttribute("loginInfo"); return commentService.getCommentList(commentVo); } @RequestMapping(value = "/insertVisitor") public @ResponseBody HashMap<String, Object> insertCommentVisitor(@RequestParam int bdNum, @RequestParam String cmtContent, HttpSession session) throws Exception { HashMap<String, Object> result = new HashMap<>(); try { LoginVo loginInfo = (LoginVo) session.getAttribute("loginInfo"); CommentVo comment = new CommentVo(); comment.setBdNum(bdNum); comment.setCmtContent(cmtContent); StringBuilder builder = new StringBuilder(session.getId()); String setWriter = builder.substring(0,2); if(loginInfo != null) { comment.setCmtWriter(loginInfo.getMemName()); comment.setEmpNum(loginInfo.getMemNum()); } else { comment.setCmtWriter("손님-" + setWriter); comment.setEmpNum(1); } commentService.insertComment(comment); result.put("status", true); } catch (Exception e) { // TODO Auto-generated catch block result.put("status", false); result.put("message", e.getMessage()); } return result; } @RequestMapping(value = "/update") public @ResponseBody HashMap<String, Object> updateComment(@RequestParam int cmtNum, @RequestParam String cmtContent) throws Exception { HashMap<String, Object> result = new HashMap<>(); try { CommentVo comment = new CommentVo(); comment.setCmtNum(cmtNum); comment.setCmtContent(cmtContent); commentService.updateComment(comment); result.put("status", true); } catch (Exception e) { result.put("status", false); result.put("message", e.getMessage()); } return result; } @RequestMapping(value = "/delete/{cmtNum}") private @ResponseBody HashMap<String, Object> deleteComment(@PathVariable int cmtNum) throws Exception { HashMap<String, Object> result = new HashMap<>(); try { commentService.deleteComment(cmtNum); result.put("status", true); } catch (Exception e) { result.put("status", false); result.put("message", e.getMessage()); } return result; } } | cs |
CommentService.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | package kr.or.infobee.comment.service; import java.util.List; public interface CommentService { public List<CommentVo> getCommentList( CommentVo commentVo) throws Exception; public void insertComment(CommentVo commentVo) throws Exception; public void updateComment(CommentVo commentVo) throws Exception; public void deleteComment(int cmtNum) throws Exception; } | cs |
CommentServiceImpl.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | package kr.or.infobee.comment.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import kr.or.infobee.comment.service.CommentService; import kr.or.infobee.comment.service.CommentVo; @Service("CommentService") public class CommentServiceImpl implements CommentService{ @Autowired private CommentMapper commentMapper; @Override public List<CommentVo> getCommentList(CommentVo commentVo) throws Exception { return commentMapper.getCommentList(commentVo); } @Override public void insertComment(CommentVo commentVo) throws Exception { commentMapper.insertComment(commentVo); } @Override public void updateComment(CommentVo commentVo) throws Exception { commentMapper.updateComment(commentVo); } @Override public void deleteComment(int cmtNum) throws Exception { commentMapper.deleteComment(cmtNum); } } | cs |
CommentMapper.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | package kr.or.infobee.comment.service.impl; import java.util.List; import org.apache.ibatis.annotations.Mapper; import kr.or.infobee.comment.service.CommentVo; @Mapper public interface CommentMapper { // 댓글 갯수 public int countComment() throws Exception; // 댓글리스트 public List<CommentVo> getCommentList(CommentVo commentVo) throws Exception; // 댓글삽입 public void insertComment(CommentVo commentVo) throws Exception; // 댓글수정 public void updateComment(CommentVo commentVo) throws Exception; // 댓글삭제 public void deleteComment(int cmtNum) throws Exception; } | cs |
CommentMapper.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="kr.or.infobee.comment.service.impl.CommentMapper"> <select id="countComment" resultType="int"> SELECT COUNT(*) FROM BOARD_COMMENT </select> <select id="getCommentList" parameterType="kr.or.infobee.comment.service.CommentVo" resultType="kr.or.infobee.comment.service.CommentVo"> SELECT cmt_num, bd_num, cmt_writer, mem_num, cmt_content, cmt_del, cmt_w_date FROM board_comment WHERE bd_num = #{bdNum} </select> <insert id="insertComment" parameterType="kr.or.infobee.comment.service.CommentVo"> INSERT INTO BOARD_COMMENT ( CMT_NUM, BD_NUM, CMT_WRITER, MEM_NUM, CMT_CONTENT, CMT_DEL, CMT_W_DATE ) VALUES ( get_seq('commentSeq'), #{bdNum}, #{cmtWriter}, #{memNum}, #{cmtContent}, 'N', now() ) </insert> <update id="updateComment" parameterType="kr.or.infobee.comment.service.CommentVo"> UPDATE BOARD_COMMENT SET CMT_CONTENT = #{cmtContent} WHERE CMT_NUM = #{cmtNum} </update> <delete id="deleteComment" parameterType="int"> DELETE FROM BOARD_COMMENT WHERE CMT_NUM = #{cmtNum} </delete> </mapper> | cs |
'IT > JSP' 카테고리의 다른 글
[JSP/Spring] 게시판 번호 역순으로 출력하기(Feat. 페이징) (0) | 2019.01.28 |
---|