본문 바로가기

개발/BACK

[SpringFramework]스프링프레임워크에서 게시판 구현 예제_3(댓글)

728x90

게시판 만들기 1 편

https://hdhdeveloper.tistory.com/20

 

[SpringFramework] 스프링환경에서 게시판 만들기_1

해당 포스팅에서는 게시판을 제작하는 글을 작성할 것이다. 나는 dataTables 라는 라이브러리를 사용해서 게시판 보드를 조금 쉽게 작성해보았다. dataTables에 대해 자세한 내용을 알고 싶다면 아래

hdhdeveloper.tistory.com

 

게시판 만들기 2편

https://hdhdeveloper.tistory.com/21

 

[SpringFramework] 스프링환경에서 게시판 만들기_2

지난 포스팅에 이어 게시판 만들기 두번 째이다. 지난 포스팅에서는 게시판 화면을 호출하는 것까지 작성했다. 이번 편에서는 게시판 자료를 등록하는 것부터 시작하겠다. 먼저 게시판 글을 작

hdhdeveloper.tistory.com


이번 포스팅에서는 댓글을 작성할 수있는 기능을 구현할 것이다

 

 

먼저 데이터베이스 테이블을 구성해야한다

아래는 테이블 생성문이다

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
CREATE TABLE `tb_reply` (
    `sid` INT(8NOT NULL,
    `reply_user` VARCHAR(50NULL DEFAULT NULL,
    `reply_content` VARCHAR(500NULL DEFAULT NULL,
    `delete_at` INT(1UNSIGNED ZEROFILL NULL DEFAULT NULL,
    `reply_no` INT(11NOT NULL AUTO_INCREMENT,
    `creat_dt` DATE NULL DEFAULT NULL,
    PRIMARY KEY (`reply_no`)
)
COLLATE='utf8_general_ci'
ENGINE=MyISAM
AUTO_INCREMENT=24
;
 
cs

reply_no는 댓글 번호로 AUTO_INCREMENT 속성을 이용해서 자동으로 순번을 입력하도록 되어있다

 

댓글을 작성하려면 먼저 게시글의 상세페이지가 필요한데,

지난 포스팅에서 게시판 상세 페이지는 작성해놓았다

 

 

 

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
<%@include file="../include_page/header.jsp" %>    
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
    
    
<!-- 2021-03-08
     댓글 한글 깨짐 현상 해결 방법
     server.xml (was 설정) 포트번호 입력공간에 URLEncoding=UTF-8 입력 후 해결-->
<html>
    <head>
        <meta charset="UTF-8">
        <!-- dataTables GRID CDN -->
        <link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css" />
        <script src="//cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"></script>
    </head>
    <body>
        <input type="hidden" value="<c:out value='${sessionConfigVO.user_name}'/>" id="session_user_name"/>
        <table id="dataTable" class="display" style="width:60%">
            <colgroup>
                <col style="width:10%"/>
                <col style="width:20%"/>
                <col style="width:30%"/>
                <col style="width:"/>
            </colgroup>
            <tbody>
                <tr>
                    <th>BOARD NUMBER</th>
                    <td id="sid"><c:out value="${result.sid }"/></td>
                    <th>TITLE</th>
                    <th><c:out value="${result.title }"/></th>
                </tr>
                <tr>
                    <th>CONTENT</th>
                    <th colspan="3"><c:out value="${result.content }"/></th>
                </tr>
                <tr>
                    <th>REPLY CNT</th>
                    <th><c:out value="${result.reply_cnt}"/></th>
                    <th>DATE</th>
                    <th><c:out value="${result.creat_dt}"/></th>
                </tr>
                <tr>
                    <th>VIEW COUNT</th>
                    <th><c:out value="${result.view_cnt}"/></th>
                    <th>WRITER</th>
                    <th><c:out value="${result.writer}"/></th>
                </tr>
            </tbody>
        </table>
        <div class="reply_div">
            <input type="button" id="reply_reg_btn" name="reply_reg_btn" class="btn btn-primary" value="GO"/>
            <input type="text" style="width:700px;" id="reply_content" name="reply_content" class="form-control"/>
            <c:forEach var="row" items="${replyResult}" varStatus="status">
                <div class="reply_list" reply_no="<c:out value='${row.reply_no}'/>" style="width:80%;height:40px;">
                    <span style="width:60%"><c:out value="${row.reply_content}"/></span>
                    <span style="width:20%"><c:out value="${row.reply_user}"/></span>
                    <span style="width:20%"><c:out value="${row.creat_dt}"/></span>
                </div>    
            </c:forEach>
        </div>
    </body>
</html>
<script type="text/javascript">
$(document).ready(function(){
    $("#dataTable").dataTable();
});
 
 
$("#reply_reg_btn").click(function(){
    $.ajax({
        url : "/reply/reply_proc.ajax",
        data : {
            sid : $("#sid").text(),
            reply_user : $("#session_user_name").val(),
            reply_content : $("#reply_content").val(),
            flag : "addRepl",
        },
        dataType : "post",
        success:function(data){
            alert("등록처리");
        }
    })
});
</script>
cs

 

class 값이 reply_div인 div태그를 보면,

입력 창과 GO라는 버튼이 생성되어있다

 

이 GO라는 버튼을 누르게 되면 작동하는 click 이벤트를 작성해 서버를 호출할 것이다

sid(게시글 번호) 값을 전달해서 해당 게시글에 작성한 댓글이라는 것을 알 수 있도록 해야한다

 

먼저 Controller를 보자

컨트롤러는 댓글 컨트롤러를 따로 생성하지 않고 기존에 존재하던 BoardController에 작성했다

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@RequestMapping(value ="/reply/reply_proc.ajax")
    public void ReplyProc(@ModelAttribute("replyVO") ReplyVO replyVO , @RequestParam String flag, HttpServletRequest request, HttpServletResponse response) throws IOException {
        boolean reply_result =false;
        switch(flag) {
            case "addRepl":
                boardService.addReply(replyVO);
                reply_result =true;
                break;
        }
        
        PrintWriter reply_writer =response.getWriter();
        response.setCharacterEncoding("UTF-8"); 
        response.setContentType("text/html;charset=UTF-8");
        reply_writer.println(reply_result);
    }
cs

 

--ReplyVO

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
package main.com.board.vo;
 
public class ReplyVO {
    private int sid;
    private String reply_user;
    private String reply_content;
    private int delete_at;
    private int reply_no;
    private String creat_dt;
    public String getReply_user() {
        return reply_user;
    }
    public void setReply_user(String reply_user) {
        this.reply_user = reply_user;
    }
    public int getSid() {
        return sid;
    }
    public void setSid(int sid) {
        this.sid = sid;
    }
    public String getReply_content() {
        return reply_content;
    }
    public void setReply_content(String reply_content) {
        this.reply_content = reply_content;
    }
    public int getDelete_at() {
        return delete_at;
    }
    public void setDelete_at(int delete_at) {
        this.delete_at = delete_at;
    }
    public int getReply_no() {
        return reply_no;
    }
    public void setReply_no(int reply_no) {
        this.reply_no = reply_no;
    }
    public String getCreat_dt() {
        return creat_dt;
    }
    public void setCreat_dt(String creat_dt) {
        this.creat_dt = creat_dt;
    }
}
 
cs

 

--boardService, boardServiceImpl, boardMapper.java, boardMapper.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
//boardService
public void addReply(ReplyVO replyVO);
public List<ReplyVO> findReplyView(int sid);
//boardServiceImpl
    @Override
    public void addReply(ReplyVO replyVO) {
        replyVO.setDelete_at(0);
        boardMapper.addReply(replyVO);
        
    }
    @Override 
    public List<ReplyVO> findReplyView(int sid) { 
        return boardMapper.findReplyView(sid); 
    }
//boardMapper.java
    public void addReply(ReplyVO replyVO);
    public List<ReplyVO> findReplyView(int sid);
//boardMapper.xml    
    <insert id="addReply">
        insert into TB_REPLY(sid,reply_user,reply_content,delete_at,creat_dt)
                values(#{sid},#{reply_user},#{reply_content},#{delete_at},sysdate())
    </insert>
        <select id="findReplyView" resultType="main.com.board.vo.ReplyVO">
        select reply_user, reply_content, reply_no,creat_dt from tb_reply where delete_at=0 and sid=#{sid}
    </select>
cs

 

그리고 지난번에 작성한 상세페이지를 조회할 때의 호출 메소드를 보면,

 

List<ReplyVO> replyResult =boardService.findReplyView(result_sid);

구문에서 

게시글 번호에 따라 댓글 데이터를 가져와 modelMap에 담아주는 것을 볼 수 있다

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
    @RequestMapping(value="/board/view.do")
    public String viewBoard(ModelMap modelMap,@RequestParam String sid) {
        BoardVO resultVO =boardService.findBoardView(sid);
        if(!SystemUtil.EmptyCheck(resultVO.getTitle())) {
            /*자료 상세 보기*/
            resultVO.setReply_cnt(boardService.ReplyCount(Integer.parseInt(sid)));
            resultVO.setView_cnt((SystemUtil.zeroRemove(resultVO.getView_cnt())));
            boardService.addViewCount(sid);
            modelMap.put("result",resultVO);
            /*해당 자료 댓 글*/
            int result_sid = Integer.parseInt(sid);
            List<ReplyVO> replyResult =boardService.findReplyView(result_sid);
            modelMap.put("replyResult", replyResult);
        }else {
            throw new RuntimeException("자료 조회 실패");
        }
        return "/board/board_view";
    }
cs

결과물 : 

 

728x90