[Spring] 스프링 부트 게시판 만들기-4 계층형 댓글 만들기

    실행화면 (계층형 댓글)

    테이블 생성

    CREATE TABLE `tb_reply` (
    `idx` INT NOT NULL AUTO_INCREMENT,
    `board_idx` INT,
    `reply_idx` INT,
    `contents` TEXT NULL,
    PRIMARY KEY (`idx`));
    

    댓글 테이블 tb_reply를 추가해줍니다. idx(댓글 번호), board_idx(글 번호), reply_idx(상위 댓글번호), contents(댓글 내용)입니다.

     

    가장 위에 있는 Root 댓글은 reply_idx가 0이고 하위 댓글들은 reply_idx로 상위댓글의 idx를 참조하도록 설계하였습니다.

     

     소스코드 

    function 추가 (view.jsp)

    function drawReply(replys) {
    	$("#cnt").text("등록된 댓글 - " + replys.length)
    	var html = '';
    	html += '<form class="form-inline" action="writeReply" method="post"><input type="hidden" name="idx" value = "' + IDX + '"><input type="hidden" name="replyIdx" value = "0"><input type="text" class="form-control mb-2 mr-sm-2" id="contents" placeholder="답글" name="contents"><button type="submit" class="btn btn-primary mb-2">등록</button></form>';
    
    	replys.forEach(function(reply){ 
    		if (reply.replyIdx == 0) {
    			var rc = 0;
    			replys.forEach(function(i){
    				if (reply.idx == i.replyIdx) rc++;
    			})
    			html += '<div class="row"><div class="col-sm-12">';
    			html += '<form class="form-inline" action="writeReply" method="post"><label for="pwd" class="mr-sm-2">' + reply.contents + '(' + rc + ')' + '</label>'
    			html += '<input type="hidden" name="idx" value = "' + IDX + '"><input type="hidden" name="replyIdx" value = "' + reply.idx + '"><input type="text" class="form-control mb-2 mr-sm-2" id="contents" placeholder="답글" name="contents"><button type="submit" class="btn btn-primary mb-2">등록</button></form>';
    			html += '<div class="row"><div class="col-sm-12 sub' + reply.idx + '"></div></div></div></div>';
    		}
    	})
    	$("#replyArea").append(html);
    	replys.forEach(function(reply){ 
    		if (reply.replyIdx != 0) {
    			var rc = 0;
    			replys.forEach(function(i){
    				if (reply.idx == i.replyIdx) rc++;
    			})
    			var subHtml = '';
    			subHtml = '<div class="row"><div class="col-sm-12 subReply">';
    			subHtml += '<form class="form-inline" action="writeReply" method="post"><label for="pwd" class="mr-sm-2">' + reply.contents + '(' + rc + ')' + '</label>'
    			subHtml += '<input type="hidden" name="idx" value = "' + IDX + '"><input type="hidden" name="replyIdx" value = "' + reply.idx + '"><input type="text" class="form-control mb-2 mr-sm-2" id="contents" placeholder="답글" name="contents"><button type="submit" class="btn btn-primary mb-2">등록</button></form>';
    			subHtml += '<div class="row"><div class="col-sm-12 sub' + reply.idx + '"></div></div></div></div>';
    			$(".sub" + reply.replyIdx).append(subHtml);
    		}
    	})
    }
    

    View.jsp의 javascript에서 댓글을 그리는 function을 추가합니다. reply_idx가 0인 root댓글을 먼저 for문을 돌리며 append시키고 나머지를 두번째 for문에서 각 댓글마다 매핑시켜주는 간단한 로직입니다.

     

    Controller (IndexController)

    @Controller
    public class IndexController {
    	
        @Autowired
        private BoardService s;
    	
        @RequestMapping(value="/replyList", method=RequestMethod.GET)
        @ResponseBody
        public List<Reply> replyList(@RequestParam("idx")int boardIdx){
            return s.getReply(boardIdx);
        }
        @RequestMapping(value="/writeReply", method=RequestMethod.POST)
        public String writeReply(
                @RequestParam("idx")int idx,
                @RequestParam("replyIdx")int replyIdx,
                @RequestParam("contents")String contents) {
            s.addReply(new Reply(0, idx,replyIdx, contents));
            return "redirect:view?idx=" + idx;
        }
    }
    

    controller에서 replyList(댓글 조회), writeReply(댓글 등록)을 구현해줍니다. 

     

    Service(BoardService)

    @Service
    public class BoardService {
        @Autowired private BoardMapper m;
    	
        public boolean addReply(Reply r) {
            return m.addReply(r);
        }
        public List<Reply> getReply(int boardIdx) {
            return m.getReply(boardIdx);
        }
    }
    

    Service에서 addReply(댓글 등록), getReply(댓글 조회)를 구현합니다.

     

    ReplyDAO

    public class Reply {
    private int idx;
    private int boardIdx;
    private int replyIdx;
    private String contents;
    public Reply() {
        // TODO Auto-generated constructor stub
    }
        public int getIdx() {
            return idx;
        }
        public void setIdx(int idx) {
            this.idx = idx;
        }
        public int getBoardIdx() {
            return boardIdx;
        }
        public void setBoardIdx(int boardIdx) {
            this.boardIdx = boardIdx;
        }
        public String getContents() {
            return contents;
        }
        public void setContents(String contents) {
            this.contents = contents;
        }
        public int getReplyIdx() {
            return replyIdx;
        }
        public void setReplyIdx(int replyIdx) {
            this.replyIdx = replyIdx;
        }
        public Reply(int idx, int boardIdx, int replyIdx, String contents) {
            super();
            this.idx = idx;
            this.boardIdx = boardIdx;
            this.replyIdx = replyIdx;
            this.contents = contents;
        }
    }
    

    댓글 객체도 하나 만들어줍니다.

     

    Mybatis

    <mapper namespace="com.web.mapper.BoardMapper">
        <insert id="addReply">
            INSERT INTO 
            tb_reply
            (
            board_idx,
            reply_idx,
            contents
            )
            VALUES
            (
            #{boardIdx},
            #{replyIdx},
            #{contents}
            )
        </insert>
        <select id="getReply" resultType="com.web.domain.Reply">
            SELECT
            idx, board_idx as boardIdx, reply_idx as replyIdx, contents
            FROM
            tb_reply
            WHERE
            board_idx = #{boardIdx}
            order by reply_idx asc
        </select>
    </mapper>
    

    댓글 등록과 댓글 조회에 필요한 쿼리문을 작성합니다.

     

     프로젝트 전체 소스(GItHub) 

    github.com/wjdxo513/spring_boot-board

     

    wjdxo513/spring_boot-board

    Contribute to wjdxo513/spring_boot-board development by creating an account on GitHub.

    github.com

    전체 프로젝트를 받으시려면 위 링크를 참고해주세요.

     

    [Spring] 스프링 부트 게시판 만들기-1 게시판 리스트 출력

    [Spring] 스프링 부트 게시판 만들기-2 게시판 글 등록 (이미지 첨부)

    [Spring] 스프링 부트 게시판 만들기-3 글 상세보기 페이지 만들기

    댓글(0)

    Designed by JB FACTORY