글 번호: 35 작성자: gihun 작성시간: 2023-03-17 20:24:05.413 조회수: 187

이 사이트의 제이쿼리 코드


let index = {
    init: function () {
        $("#btn-save").on("click", () => {
            this.save();
        });
        $("#btn-delete").on("click", () => {
            this.deleteById();
        });
        $("#btn-update").on("click", () => {
            this.update();
        });
        $("#btn-reply-save").on("click", () => {
            this.replySave();
        });
    },

    // 수정해야할 부분입니다.
    save: function () {
        let data = {
            title: $("#title").val(),
            content: editor.getHTML(),
            id: $("#id").val()
        }

        $.ajax({
            type:"POST",
            url:"/api/board",
            data:JSON.stringify(data), // http body 데이터
            contentType: "application/json; charset=utf-8",
            dataType:"JSON"
        }).done(function (res) {
            alert("등록이 완료되었습니다.")
            location.href = "/board/"+id;
        }).fail(function (err) {
            // alert(JSON.stringify(err));
            // 로그인 페이지로 이동
            alert("로그인 해주세요.");
            location.href = "/auth/loginForm";
        });
    },

    deleteById: function() {
        let id =$("#id").text();

        $.ajax({
            type:"DELETE",
            url:"/api/board"+id,
            dataType:"JSON"
        }).done(function (res) {
            alert("삭제가 완료되었습니다.")
            location.href = "/blog";
        }).fail(function (err) {
            alert(JSON.stringify(data));
        });
    },

    update: function () {
        let id = $("#id").val();
        console.log(id);

        let data = {
            title: $("#title").val(),
            content: editor.getHTML(),
            boardId: $("#boardId").val(),
        }

        $.ajax({
            type:"PUT",
            url:"/api/board"+id,
            data:JSON.stringify(data), // http body 데이터
            contentType: "application/json; charset=utf-8",
            dataType:"JSON"
        }).done(function (res) {
            console.log(data.boardId);
            alert("등록이 완료되었습니다.")
            // 절대경로
            location.href = `/board/${data.boardId}`;
        }).fail(function (err) {
            // alert(JSON.stringify(err));
            // 로그인 페이지로 이동
            alert("로그인 해주세요.");
            location.href = "/auth/loginForm";
        });
    },


    replySave: function ()
        {
        let data = {
            userId: $("#userId").val(),
            boardId: $("#boardId").val(),
            content: $("#reply-content").val()
        }

        console.log(data);

        $.ajax({
            type:"POST",
            url:`/api/board/${data.boardId}/reply`,
            data:JSON.stringify(data), // http body 데이터
            contentType: "application/json; charset=utf-8",
            dataType:"JSON"
        }).done(function (res) {
            alert("등록 완료되었습니다.")
            location.href = `/board/${data.boardId}`;
        }).fail(function (err) {
            // alert(JSON.stringify(err));
            // 로그인 페이지로 이동
            alert("로그인 해주세요.");
            location.href = "/auth/loginForm";
        });
    },

    replyDelete: function (boardId, replyId)
    {
        $.ajax({
            type:"DELETE",
            url:`/api/board/${boardId}/reply/${replyId}`,
            dataType:"JSON"
        }).done(function (res) {
            alert("삭제 완료되었습니다.")
            location.href = "/blog";
        }).fail(function (err) {
            alert(JSON.stringify(err));
        });
    },



}

index.init();

이 사이트의 게시판 컨트롤러 부분

package com.study.board.controller.api;


import com.study.board.config.auth.PrincipalDetail;
import com.study.board.controller.dto.ReplySaveRequestDto;
import com.study.board.controller.dto.ResDto;
import com.study.board.model.Board;
import com.study.board.service.BoardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

@RestController
public class BoardApiController {

    @Autowired
    private BoardService boardService;

    // 글 작성
    @PostMapping("/api/board")
    public ResDto<Integer> save(@RequestBody Board board, @AuthenticationPrincipal PrincipalDetail principal){
        boardService.글쓰기(board, principal.getUser());
        return new ResDto<Integer>(HttpStatus.OK.value(), 1); // 자바오브젝트를 JSON으로 변환해서 리턴(Jackson)
    }

    @DeleteMapping("/api/board{id}")
    public ResDto<Integer> deleteById(@PathVariable int id) {
        boardService.글삭제하기(id);
        return new ResDto<Integer>(HttpStatus.OK.value(), 1);
    }

    @PutMapping("/api/board{id}")
    public ResDto<Integer> update(@PathVariable int id, @RequestBody Board board) {
        boardService.글수정하기(id, board);
        return new ResDto<Integer>(HttpStatus.OK.value(), 1);
    }

    // 데이터를 받을 때 컨트롤러에서 dto를 만들어서 받는게 좋다.
    // 이건 작은 프로젝트라 dto 안씀

    @PostMapping("/api/board/{boardId}/reply")
    public ResDto<Integer> replySave(@RequestBody ReplySaveRequestDto replySaveRequestDto)
    {
        boardService.댓글쓰기(replySaveRequestDto);
        return new ResDto<Integer>(HttpStatus.OK.value(), 1); // 자바오브젝트를 JSON으로 변환해서 리턴(Jackson)
    }

    @DeleteMapping("/api/board/{boardId}/reply/{replyId}")
    public ResDto<Integer> replyDelete(@PathVariable int replyId)
    {
        boardService.댓글삭제(replyId);
        return new ResDto<Integer>(HttpStatus.OK.value(), 1);
    }
}

package com.study.board.controller;

import com.study.board.config.auth.PrincipalDetail;
import com.study.board.service.BoardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@Controller
public class BoardController {

    @Autowired
    private BoardService boardService;

    @GetMapping({"", "/"})
    public String index(Model model,
                        @PageableDefault(size=3, sort="id",
                                direction= Sort.Direction.DESC)
                        Pageable pageable) {
        model.addAttribute("boards", boardService.글목록(pageable));
        return "/index";
    }

    @GetMapping("/board/{id}")
    public String findById(@PathVariable int id, Model model) {
        model.addAttribute("board", boardService.글상세보기(id));
        return "board/detail";
    }

    @GetMapping("/board/{id}/updateForm")
    public String  updateForm(@PathVariable int id, Model model) {
        model.addAttribute("board", boardService.글상세보기(id));
        return "board/updateForm";
    }

    // USER 권한이 필요
    @GetMapping("/board/saveForm")
    public String saveForm() {
        return "board/saveForm";
    }
}



댓글 리스트

Created by 송바래

✉ gihun3645@naver.com

🚩경기도, 성남시