Dev.GA

[spring/게시판] #8 게시판 댓글달기(Ajax) - (1) 본문

Dev.Project/project1-spring게시판

[spring/게시판] #8 게시판 댓글달기(Ajax) - (1)

Dev.GA 2018. 3. 19. 02:17



개발환경

Server OS : Windows10

Language : JAVA 1.6

Framework : Spring 3.1.1

WEB Server : Apache 

WAS Server : Tomcat 7

build tool : maven 2.5.1

DB : MySQL 5.7.16

ORM : mybatis 3.2.7


8. 게시판 댓글달기(Ajax) - (1)



이번 포스팅은 지난번 답글달기에 이어 댓글작성 기능을 추가해 보겠다.


먼저, 댓글을 저장할 테이블을 만들어보자.


1
2
3
4
5
6
7
8
CREATE TABLE `comment` (
  `c_code` INT(10NOT NULL AUTO_INCREMENT,
  `b_code` INT(10NOT NULL,
  `comment` LONGTEXT,
  `writer` VARCHAR(50DEFAULT NULL,
  `reg_datetime` DATETIME DEFAULT NULL,
  PRIMARY KEY (`c_code`)
ENGINE=INNODB DEFAULT CHARSET=utf8mb4
cs

테이블의 필드를 보면,


c_code : 댓글(comment)의 고유번호, key


b_code : 댓글을 달 원글의 글번호가 된다. board테이블의 글번호(code)


나머지는 해당 내용과 글쓴이 등으로 구성되며, 다음 포스팅에서 이 댓글에 댓글을 달아볼때 필드를 추가하겠다.


이제 댓글 등록을 위한 댓글 폼(form)을 만들겠다. comment.jsp라는 페이지를 만들었는데 다음과 같이 구성되어 있다.



이 comment,jsp는 단독으로 불리는 화면이 아니다.


원글을 상세보기를 통해 확인 시 원글의 하단부에 다음과 같이 삽입될 것이다.


viewForm.jsp의 댓글 내용 하단부에 다음과 같이 코드를 추가하여 comment.jsp를 삽입해준다.


<%@ include file="../common/comment.jsp" %>


그럼 comment.jsp가 들어가게 되며 화면으로 확인하자.



그럼 comment.jsp를 보자.


comment.jsp

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
116
117
118
119
120
121
122
123
124
125
126
<%@ page contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <link rel="stylesheet" href="/css/bootstrap.css">
</head>
<body>
<div class="container">
    <form id="commentForm" name="commentForm" method="post">
    <br><br>
        <div>
            <div>
                <span><strong>Comments</strong></span> <span id="cCnt"></span>
            </div>
            <div>
                <table class="table">                    
                    <tr>
                        <td>
                            <textarea style="width: 1100px" rows="3" cols="30" id="comment" name="comment" placeholder="댓글을 입력하세요"></textarea>
                            <br>
                            <div>
                                <a href='#' onClick="fn_comment('${result.code }')" class="btn pull-right btn-success">등록</a>
                            </div>
                        </td>
                    </tr>
                </table>
            </div>
        </div>
        <input type="hidden" id="b_code" name="b_code" value="${result.code }" />        
    </form>
</div>
<div class="container">
    <form id="commentListForm" name="commentListForm" method="post">
        <div id="commentList">
        </div>
    </form>
</div>
 
<script>
/*
 * 댓글 등록하기(Ajax)
 */
function fn_comment(code){
    
    $.ajax({
        type:'POST',
        url : "<c:url value='/board/addComment.do'/>",
        data:$("#commentForm").serialize(),
        success : function(data){
            if(data=="success")
            {
                getCommentList();
                $("#comment").val("");
            }
        },
        error:function(request,status,error){
            //alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
       }
        
    });
}
 
/**
 * 초기 페이지 로딩시 댓글 불러오기
 */
$(function(){
    
    getCommentList();
    
});
 
/**
 * 댓글 불러오기(Ajax)
 */
function getCommentList(){
    
    $.ajax({
        type:'GET',
        url : "<c:url value='/board/commentList.do'/>",
        dataType : "json",
        data:$("#commentForm").serialize(),
        contentType: "application/x-www-form-urlencoded; charset=UTF-8"
        success : function(data){
            
            var html = "";
            var cCnt = data.length;
            
            if(data.length > 0){
                
                for(i=0; i<data.length; i++){
                    html += "<div>";
                    html += "<div><table class='table'><h6><strong>"+data[i].writer+"</strong></h6>";
                    html += data[i].comment + "<tr><td></td></tr>";
                    html += "</table></div>";
                    html += "</div>";
                }
                
            } else {
                
                html += "<div>";
                html += "<div><table class='table'><h6><strong>등록된 댓글이 없습니다.</strong></h6>";
                html += "</table></div>";
                html += "</div>";
                
            }
            
            $("#cCnt").html(cCnt);
            $("#commentList").html(html);
            
        },
        error:function(request,status,error){
            
       }
        
    });
}
 
</script>
 
</body>
</html>
cs


댓글을 작성하는 방법은 Ajax로 구현하였다. 나는 게시물에 댓글을 달았는데 아무런 영향이 없는 게시물이 다시 로딩되는 행위는 불필요하다.

그래서 내가 원하는 댓글 부분만 로딩되도록 Ajax를 구현하였다. 이는 추후에 댓글에 댓글을 달때도 당연하게 적용될 것이다.


48번째 라인) fn_comment() 함수를 통해 댓글을 등록하고 등록이 정상적으로 수행되면 등록과 동시에 57번째 라인) getCommentList() 함수를 호출한다. getCommentList() 함수는 해당 게시물의 댓글리스트를 불러오는 역할을 한다. 이 역시 Ajax로 구현하였다. 해당 게시물의 댓글을 불러와 95번재 라인) html코드로 해당 게시물을 뿌려주는 역할을 한다. 마지막 113번째 라인) 에서 상단에 미리 만들어 놓은 댓글리스트폼(commentListForm)에 삽입시켜주면 된다.


이제 Ajax를 통해 호출된 Controller부분을 보자.


BoardController.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
@Controller
public class BoardController {
 
    @Autowired
    private BoardService boardServiceImpl;
 
... 생략 ...
 
    /**
     * 댓글 등록(Ajax)
     * @param boardVO
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/board/addComment.do")
    @ResponseBody
    public String ajax_addComment(@ModelAttribute("boardVO") BoardVO boardVO, HttpServletRequest request) throws Exception{
        
        HttpSession session = request.getSession();
        LoginVO loginVO = (LoginVO)session.getAttribute("loginVO");
        
        try{
        
            boardVO.setWriter(loginVO.getUser_id());        
            boardServiceImpl.addComment(boardVO);
            
        } catch (Exception e){
            e.printStackTrace();
        }
        
        return "success";
    }
    
    /**
     * 게시물 댓글 불러오기(Ajax)
     * @param boardVO
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/board/commentList.do", produces="application/json; charset=utf8")
    @ResponseBody
    public ResponseEntity ajax_commentList(@ModelAttribute("boardVO") BoardVO boardVO, HttpServletRequest request) throws Exception{
        
        HttpHeaders responseHeaders = new HttpHeaders();
        ArrayList<HashMap> hmlist = new ArrayList<HashMap>();
        
        // 해당 게시물 댓글
        List<BoardVO> commentVO = boardServiceImpl.selectBoardCommentByCode(boardVO);
        
        if(commentVO.size() > 0){
            for(int i=0; i<commentVO.size(); i++){
                HashMap hm = new HashMap();
                hm.put("c_code", commentVO.get(i).getC_code());
                hm.put("comment", commentVO.get(i).getComment());
                hm.put("writer", commentVO.get(i).getWriter());
                
                hmlist.add(hm);
            }
            
        }
        
        JSONArray json = new JSONArray(hmlist);        
        return new ResponseEntity(json.toString(), responseHeaders, HttpStatus.CREATED);
        
    }
}
cs


댓글 등록 부분 18번째 라인) 을 보면 Ajax로 Controller를 호출할때 해당 페이지의 form데이터를 serialize()로 하여 가져왔기에 form데이터는 boardVO에 속해있어 바로 등록자만 추가하여 댓글을 insert해주면 된다.


댓글 불러오는 부분 42번째 라인) 을 보면 Ajax에서 호출시 dataType을 json형태로 지정해주었기에(comment.jsp의 85번째 라인)

해당 게시물의 댓글을 List로 받아와 JSONArray형태로 데이터를 넘겨주었다.


JSONArray를 사용하려면 pom.xml에 dependency를 추가해주어야 한다.


<!-- https://mvnrepository.com/artifact/org.json/json -->

<dependency>

    <groupId>org.json</groupId>

    <artifactId>json</artifactId>

    <version>20180130</version>

</dependency>



댓글을 등록하면 아래와 같이 Ajax로 구현하였기에 등록한 댓글 밑으로 순차적으로 계속 댓글이 추가된다.



다음 포스팅에서는 Ajax를 계속 활용하여 댓글 수정/삭제와 댓글에 댓글을 추가해보도록 하겠다.



Comments