[Spring Boot] Restful API의 구성

Coco Park·2024년 1월 24일
0

Spring_Boot

목록 보기
12/13

Restful API의 개요

기존에는 Controller에서의 Mapping을 Get방식이나 Post방식으로만 구성하였다.

이런 경우에 수정이나 삭제의 경우에도 PostMappping으로 구현한다면, 삭제를 할 수 없는 경우(처음부터 삭제를 호출하는 경우)에 서버로 요청을 일단 보내기 때문에 효과적이지 못한 구현이라고 할 수 있다.

즉, 이를 해결하기 위해 PutMapping / DeleteMapping을 사용하여 갱신하는 경우와 삭제하는 경우에 대해 정의해두면 같은 URL을 가지고도 여러가지의 호출을 Mapping할 수 있다는 장점이 있다.

이를 멱등성이라고 하는데, 사용자가 의도한 대로만 서버에서 요청을 보낸다는 것을 의미한다.

앞서 게시글 작성에서는 Get/PostMapping으로만 구현하였으나, 이번 공지사항에 대한 구현은 Put/DeleteMapping을 활용하여 구현하고자 하였다.

View / Service / Controller 단은 앞서 구현하였던 게시글과 동일하게 구현하면 되므로 템플릿과 소스코드들은 대부분 유사하게 사용하였다.

따라서, ajax로 URL을 호출하는 코드와 이를 받는 Controller단의 코드 위주로 확인해보고자 한다.

- DeleteMapping -

// javascript - DeleteMapping //
    $("#btn-notice-delete").click(function () {
		// 현재 유저와 공지 작성자를 비교하기 위한 변수
        var nowUser = $("#nowId").val();
        var noticeWriter = $("#noticeWriter").val();
        var noticeId = $("#nid").val();
		// 현재 유저와 공지 작성자를 비교하여 삭제할 것인지를 묻는 코드
        if (nowUser === noticeWriter) {
            if (confirm("삭제하시겠습니까?")) {
                $.ajax({
                    type : "delete", // DeleteMapping의 구현
                    url : "/notice/delete?nid=" + noticeId,
                    beforeSend : function(xhr) {xhr.setRequestHeader(header, token);}, 
                    // Get 방식이 아니면 모두 CSRF에 대한 설정을 해야함..
                    contentType : "json",
                    success : function() {
                        alert("삭제되었습니다!!");
                        window.location.href = "/notice";
                    }
                })
            }
        } else {
            alert("작성자와 현재 유저가 다릅니다!!");
        }
    })
// NoticeController - DeleteMapping //
@ResponseBody
@DeleteMapping("/notice/delete")
    public void noticeDelete(@RequestParam(value="nid") Long nid) {
        noticeService.deleteNotice(nid);
    }
// Service에서 Repository를 호출하는 코드는 Post방식과 동일함 //

View 단에서의 호출

DeleteMapping이 호출된 모습

- PutMapping -

// javascript - PutMapping //
// 1. 수정 페이지를 Get 방식으로 호출 //
$("#btn-notice-modify").click(function () {
	// 현재 작성자와 접속 유저 비교 
    var nowUser = $("#nowId").val();
    var noticeWriter = $("#noticeWriter").val();
    var noticeId = $("#nid").val();
	// 비교 구문
    if (nowUser === noticeWriter) {
    	if (confirm("수정하시겠습니까?")) {
            window.location.href = "/notice/modifyPage?nid=" + noticeId;
        }
   } else {
        alert("작성자와 현재 유저가 다릅니다!!");
    }
})
// 2. 수정 페이지에서 수정한 내용을 PutMapping에 전달 //
    $("#btn-notice-modifyConfirm").click(function () {
		// 변경할 내용들을 JSON 형태로 받음 
        var noticeModify = {
            "noticeId" : $("#nid").val(),
            "noticeWriter" : noticeWriter,
            "noticeModifyTitle" : $("#noticeTitle").val(),
            "noticeModifyContent" : $("#noticeContent").val()
        }
		// ajax에서 PutMapping 역시 CSRF 설정을 필요로 함
        if (confirm("해당 내용으로 수정하시겠습니까?")) {
            $.ajax({
                type : "put",
                url : "/notice/modify",
                data : JSON.stringify(noticeModify),
                beforeSend : function(xhr) {xhr.setRequestHeader(header, token);},
                contentType : "application/json; charset=UTF-8",
                success : function() {
                    alert("수정완료되었습니다!!");
                    window.location.href="/notice/" + $("#nid").val();
                }
            })
        }
    })
@ResponseBody
@PutMapping("/notice/modify")
    public void noticeModify(@RequestBody Map<String, Object> map) {
    	// 업데이트를 위해 기존 공지사항의 정보를 받아옴
        NoticeDTO noticeDTO = noticeService.getNotice(Long.valueOf((String) map.get("noticeId")));
		// 기존 공지사항 DTO 데이터에 수정하기 위해 VIEW단에서 전달한 데이터로 세팅함
        noticeDTO.setNoticeTitle((String) map.get("noticeModifyTitle"));
        noticeDTO.setNoticeWriter((String) map.get("noticeWriter"));
        noticeDTO.setNoticeContent((String) map.get("noticeModifyContent"));
        noticeDTO.setModTime(String.valueOf(LocalDate.now()));
		// Service 단에서의 Repository는 Post방식과 동일하게 작성
        noticeService.modifyNotice(noticeDTO);
    }

View 단에서 호출

수정 페이지 호출

수정된 결과

PutMapping이 호출된 모습

이처럼 Put/DeleteMapping을 구성하면 PostMapping으로 구성할 때 보다 더 효율적으로 구성할 수 있다.

추가적으로 구현할 사항

공지사항은 모든 유저들이 확인할 수 있지만 관리자만 작성/수정/삭제가 가능하므로 권한에 대한 설정을 추후에 구현할 것이다.

profile
ヽ(≧□≦)ノ

0개의 댓글