09009

[Spring Boot] 게시판 연습 (8) - 댓글 작성 내용 서버로 요청하기 본문

Back-End/Spring
[Spring Boot] 게시판 연습 (8) - 댓글 작성 내용 서버로 요청하기
09009

detail.html

jquery cdn

<script src="https://code.jquery.com/jquery-3.7.1.js"></script>

 

코드 추가

* input 태그에 접근하기 때문에 value 속성에 접근이 가능하다는 것을 인지할 것.

<button onclick="listReq()">목록</button>
<button onclick="updateReq()">수정</button>
<button onclick="deleteReq()">삭제</button>

<!-- 댓글 작성 부분 -->
<div id="comment-write">
    <input type="text" id="commentWriter" placeholder="작성자">
    <input type="text" id="commentContents" placeholder="내용">
    <button id="comment-write-btn" onclick="commentWrite()">댓글작성</button>
</div>
<!-- 댓글 출력 부분 -->
<div id="comment-list">


</div>

 

현재까지의 전체 코드

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>detail</title>
    <!-- jquery cdn -->
    <script src="https://code.jquery.com/jquery-3.7.1.js"></script>
</head>
<body>
<table>
    <tr>
        <th>id</th>
        <td th:text="${board.id}"></td>
    </tr>
    <tr>
        <th>title</th>
        <td th:text="${board.boardTitle}"></td>
    </tr>
    <tr>
        <th>writer</th>
        <td th:text="${board.boardWriter}"></td>
    </tr>
    <tr>
        <th>date</th>
        <td th:text="${board.boardCreatedTime}"></td>
    </tr>
    <tr>
        <th>hits</th>
        <td th:text="${board.boardHits}"></td>
    </tr>
    <tr>
        <th>contents</th>
        <td th:text="${board.boardContents}"></td>
    </tr>
    <tr th:if="${board.fileAttached == 1}">
        <th>image</th>
        <td th:each="fileName : ${board.storedFileName}">
            <img th:src="@{|/upload/${fileName}|}" alt="">
        </td>
    </tr>


</table>
<button onclick="listReq()">목록</button>
<button onclick="updateReq()">수정</button>
<button onclick="deleteReq()">삭제</button>

<!-- 댓글 작성 부분 -->
<div id="comment-write">
    <input type="text" id="commentWriter" placeholder="작성자">
    <input type="text" id="commentContents" placeholder="내용">
    <button id="comment-write-btn" onclick="commentWrite()">댓글작성</button>
</div>
<!-- 댓글 출력 부분 -->
<div id="comment-list">


</div>

</body>
<script th:inline="javascript">
    const commentWrite = () => {
        const writer = document.getElementById("commentWriter").value;
        const contents = document.getElementById("commentContents").value;
        console.log("작성자 : ", writer);
        console.log("내용 : ", contents);
    }



    const listReq = () => {
        console.log("목록 요청");
        const page = [[${page}]];
        location.href = "/board/paging?page=" + page;
    }
    const updateReq = () => {
        console.log("수정 요청");
        const id = [[${board.id}]];
        location.href = "/board/update/" + id;
    }
    const deleteReq = () => {
        console.log("삭제 요청");
        const id = [[${board.id}]];
        location.href = "/board/delete/" + id;
    }
</script>
</html>

 

여기까지 작성하고 실행

 

댓글은 어떤 게시글에 작성된 댓글인지의 여부가 중요하다. 게시글번호가 반드시 같이 저장되어야 한다.

 

댓글 작성 ajax 코드 추가

    const commentWrite = () => {
        const writer = document.getElementById("commentWriter").value;
        const contents = document.getElementById("commentContents").value;
        console.log("작성자 : ", writer);
        console.log("내용 : ", contents);
        const id = [[${board.id}]]; // 게시글번호
        $.ajax({
            // 요청방식: post, 요청주소: /comment/save, 요청데이터: 작성자, 작성내용, 게시글번호
            type: "post",
            url: "/comment/save",
            data: {
                "commentWriter": writer,
                "commentContents": contents,
                "boardId": id
            },
            success: function(res) {
                console.log("요청 성공", res);
            },
            error: function(err) {
                console.log("요청 실패", err);
            }
        });
    }

 

CommentDTO 생성

package com.yyi.board.dto;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.time.LocalDateTime;

@Getter
@Setter
@ToString
public class CommentDTO {
    private Long id;
    private String commentWriter;
    private String commentContents;
    private Long boardId;
    private LocalDateTime commentCreatedTime;
}

 

CommentController 생성

package com.yyi.board.controller;

import com.yyi.board.dto.CommentDTO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequiredArgsConstructor
@RequestMapping("/comment")
public class CommentController {

    @PostMapping("/save")
    public String save(@ModelAttribute CommentDTO commentDTO) {
        System.out.println("commentDTO = " + commentDTO);
        return "요청 성공";
    }

}

 

여기까지 작성하고 다시 실행 후 댓글 작성해보기