⁂ MyBatis Framework/: 기본 익히기

[MyBatis] #5-2 AJAX를 활용한 댓글 게시판 만들기 2 - 댓글 등록(Insert)

김갱환 2022. 11. 14. 14:59

 

1. Model

 * 짚고 넘어갈 뽀인트

-  insert문 작성

 

1) content.xml

<insert id="insert" parameterType="kr.co.itwill.comment.CommentDTO">
    <![CDATA[
    INSERT INTO pcomment(cno, pno, content, wname)
    VALUES (pcomment_seq.nextval, #{pno}, #{content}, #{wname})
    ]]>
</insert>

 

2) contentDAO.java

public int commentInsert(CommentDTO comment) {
    return sqlSession.insert("comment.insert", comment);
} // commentInsert() end

 

 

2. View

 * 짚고 넘어갈 뽀인트

- 댓글이 들어가고, 추가될 div 영역 생성.

- 버튼 클릭시 자바 스크립트로 function 구현.

 

<!-- 댓글 -->
<div class="container">
    <label for="content">댓글</label>
    <form name="commentInsertForm" id="commentInsertForm">
    <div>
        <input type="hidden" name="pno" id="pno" value="${product.PRODUCT_CODE}">
        <input type="text" name="content" id="content" placeholder="내용을 입력하세요">
        <button type="button" name="commentInsertBtn" id="commentInsertBtn">등록</button>
    </div>
    </form>
</div>
<hr>
<div class="container">
    <div class="commentList"></div>
</div>
<!-- 댓글 관련 자바스크립트 -->
<script>
    let pno='${product.PRODUCT_CODE}';

    $('#commentInsertBtn').click(function(){
        let insertData = $('#commentInsertForm').serialize();
        alert(insertData);
        commentInsert(insertData);
    }); // click() end

    // 댓글 등록
    function commentInsert(insertData){
        $.ajax({
             url:'/comment/insert'
            ,type:'post'
            ,data:insertData
            ,success:function(data){
                if(data==1){
                    commentList(); // 댓글 작성 후 댓글 목록 함수 호출
                    $('#content').val('');
                } // if end
            } // success end
        }); // ajax() end
    }; // commentInsert() end
</script>

 

 

3. Controller

 * 짚고 넘어갈 뽀인트

- insert 명령어 생성

- DTO를 활용하여 키값 저장

 

@ResponseBody
@RequestMapping("/insert")
private int mCommentServiceInsert(@RequestParam int pno, @RequestParam String content) throws Exception {
    CommentDTO comment = new CommentDTO();
    comment.setPno(pno);
    comment.setContent(content);
    // 로그인 기능을 구현했거나 따로 댓글 작성자를 입력받는 폼이 있다면 입력받아온 값을 사용하면 된다.
    // 따로 구현하지 않았기 때문에 아이디는 임시로 "test"
    comment.setWname("test");
    return commentDao.commentInsert(comment);

} // mCommentServiceInsert() end