카테고리 없음

#61. AJAX JSON /GSON 일반게시글(댓글조회, 댓글작성) , 짭채팅

열하나요 2023. 9. 26. 09:43

61-1. GSON다운

Google JSON 라이브러리 다운

https://mvnrepository.com/

JSON Libraries > GSON > 2.8.5 (사람들이 많이쓰는거) >  jar

 

 

 

61-1. 

 

61-2. 댓글조회

1. boardDetailView.jsp

댓글화면

    <div id="reply-area">
        <table border="1" align="center">
            <thead>
                <tr>
                    <th>댓글작성</th>
                    <% if(loginUser != null) { %>
                        <td>
                            <textarea id="replyContent" cols="50" rows="3" style="resize:none;"></textarea>
                        </td>
                        <td><button onclick="insertReply();">댓글등록</button></td>    					
                    <% } else { %>
                        <td>
                            <textarea readonly cols="50" rows="3" style="resize:none;">로그인 후 이용가능한 서비스입니다.</textarea>
                        </td>
                        <td><button>댓글등록</button></td>
                    <% } %>
                </tr>
            </thead>
            <tbody>

            </tbody>
        </table>

    </div>
</div>


<script>
    function selectReplyList(){

        $.ajax({
            url : 'rlist.do',
            data : {bno : <%= b.getBoardNo() %>},
            success : function(result){
                console.log(result);

                // 댓글 개수만큼 반복
                let resultStr = '';
                for(let i in result){

                    resultStr += '<tr>'
                               + '<td>' + result[i].replyWriter + '</td>'
                               + '<td>' + result[i].replyContent + '</td>'
                               + '<td>' + result[i].createDate + '</td>'
                               + '</tr>'
                }
                $('#reply-area tbody').html(resultStr);

            },
            error : function(){
                console.log('댓글 읽어오기 실패~');
            }
        })
    }

    $(function(){
        selectReplyList();

    });

    function insertReply(){

        $.ajax({
            url : 'rinsert.do',
            type : 'post',
            data : {
                bno : <%= b.getBoardNo() %>,
                content : $('#replyContent').val()
                // 작성자는 controller에서 뽑아보자
            },
            success : function(result){
                // console.log(result);

                if(result > 0){
                    // 잘써지면 textarea에 써진 내용은 날라가게
                    $('#replyContent').val('');

                    // 댓글이 써진것이 포함되어 다시 조회되게
                    selectReplyList();
                }
            },
            error : function(){
                console.log('ㅠㅠ');
            }
        })
    }
</script>

 

 

2. Reply.java VO 생성

4개짜리 생성자 만들기~~

package com.kh.jsp.board.model.vo;

public class Reply {
	
//	REPLY_NO	NUMBER
//	REPLY_CONTENT	VARCHAR2(400 BYTE)
//	REF_BNO	NUMBER
//	REPLY_WRITER	NUMBER
//	CREATE_DATE	DATE
//	STATUS	VARCHAR2(1 BYTE)
	
	private int replyNo;
	private String replyContent;
	private int refBno;
	private String replyWriter; // boardNo로 가져오지만, 작성자는 문자열이므로 String으로 받자.
	private String createDate; // Date도 굳이 날짜로 가져올 필요는 없으니 문자열 String으로 받자.
	private String status; // 얘도 사실 char형인데 String으로 받자.
    
    
    
    public Reply(int replyNo, String replyContent, String replyWriter, String createDate) {
    super();
    this.replyNo = replyNo;
    this.replyContent = replyContent;
    this.replyWriter = replyWriter;
    this.createDate = createDate;
	}
}

 

3. AjaxReplyListController.java

mapping값 "/rlist.do"

댓글조회를 도와줄 Controller

@WebServlet("/rlist.do")
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    // GET => 인코딩X (POST여도 굳이 숫자만 넘어오는데 한글깨짐방지를 위한 인코딩을 해야할까?)

    // 값 뽑기
    int boardNo = Integer.parseInt(request.getParameter("bno"));
    // VO 가공

    // Service 요청 => BoardService
    ArrayList<Reply> list = new BoardService().selectReplyList(boardNo);

    // 응답
    // GSON을 이용해보자 ~! => ArrayList를 JSON타입의 데이터로 변환
    // 형식, 인코딩
    response.setContentType("application/json; charset=UTF-8");

    new Gson().toJson(list, response.getWriter());
}

 

4. BoardService.java

// 댓글 조회(ajax)
public ArrayList<Reply> selectReplyList(int boardNo){

    Connection conn = getConnection();

    ArrayList<Reply> list = new BoardDao().selectReplyList(conn, boardNo);

    close(conn);

    return list;
}

 

5. BoardDao.java

// 댓글조회(ajax)
public ArrayList<Reply> selectReplyList(Connection conn, int boardNo){

    ArrayList<Reply> list = new ArrayList();
    PreparedStatement pstmt = null;
    ResultSet rset = null;
    String sql = prop.getProperty("selectReplyList");

    try {
        pstmt = conn.prepareStatement(sql);
        pstmt.setInt(1, boardNo);

        rset = pstmt.executeQuery();

        while(rset.next()) {
            list.add(new Reply(rset.getInt("REPLY_NO"),
                               rset.getString("REPLY_CONTENT"),
                               rset.getString("USER_ID"),
                               rset.getString("CREATE_DATE")));
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        close(rset);
        close(pstmt);
    }
    return list;
}

 

6. mapper-board.xml SQL문

<!-- 댓글 조회(ajax) -->
<entry key="selectReplyList">
    SELECT
           REPLY_NO,
           REPLY_CONTENT,
           USER_ID,
           TO_CHAR(CREATE_DATE, 'YY/MM/DD HH:MI:SS') CREATE_DATE
      FROM 
           REPLY
      JOIN
           MEMBER ON(REPLY_WRITER = USER_NO)
     WHERE 
           REF_BNO = ?
       AND 
           REPLY.STATUS = 'Y'
     ORDER
        BY
           CREATE_DATE DESC
</entry>

 

 

61-3. 댓글 작성

1. AjaxInsertReplyController.java

@WebServlet("/rinsert.do")
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    // POST => 인코딩
    request.setCharacterEncoding("UTF-8");

    // request로부터 값 뽑기
    int boardNo = Integer.parseInt(request.getParameter("bno"));
    String replyContent = request.getParameter("content");

    // 로그인한 회원정보
    int userNo = ((Member)request.getSession().getAttribute("loginUser")).getUserNo();

    // VO로 가공 => Reply
    Reply r = new Reply();
    r.setRefBno(boardNo);
    r.setReplyContent(replyContent);
    r.setReplyWriter(String.valueOf(userNo));

    // Service 요청
    int result = new BoardService().insertReply(r);

    // Gson, Json => 넘겨야 할 값이 여러 개일 때
    // 넘겨야 할 값이 result

    response.setContentType("text/html; charset=UTF-8");
    response.getWriter().print(result);
}

 

2. BoardService.java

// 댓글 작성(ajax)
public int insertReply(Reply r) {

    Connection conn = getConnection();

    int result = new BoardDao().insertReply(conn, r);

    if(result > 0) {
        commit(conn);
    } else {
        rollback(conn);
    }
    return result;
}

 

3. BoardDao.java

// 댓글 작성(ajax)
public int insertReply(Connection conn, Reply r) {

    int result = 0;
    PreparedStatement pstmt = null;
    String sql = prop.getProperty("insertReply");

    try {
        pstmt = conn.prepareStatement(sql);

        pstmt.setString(1, r.getReplyContent());
        pstmt.setInt(2, r.getRefBno());
        pstmt.setInt(3, Integer.parseInt(r.getReplyWriter()));

        result = pstmt.executeUpdate();
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        close(pstmt);
    }
    return result;
}

 

4. mapper-board.xml

<entry key="insertReply">
    INSERT
      INTO 
           REPLY
           (
           REPLY_NO,
           REPLY_CONTENT,
           REF_BNO,
           REPLY_WRITER
           )
    VALUES
           (
           SEQ_RNO.NEXTVAL,
           ?,
           ?,
           ?		 	   
           )
</entry>

 

61-4. 짭채팅

boardDetailView.jsp

// 짭 채팅
// 일반창과 시크릿창으로 ㅎㅎ
// 댓글창에 ㄱㄱ
$(function(){

    selectReplyList();

    setInterval(selectReplyList, 1000);
})
// 짭 채팅 끝

이렇게 댓글처럼 채팅테이블 하나 만들어서 채팅기능 구현하면 될 듯!

 

기능구현 끝!