Book/Spring boot 와 AWS로 혼자 구현하는 웹서비스

[Book] 17) 수정 및 삭제 기능을 만들어보자!

kkkkkkkkkkkk 2022. 4. 2. 21:43

😀  화면 구성해보기!

{{>layout/header}}

<h1>게시글 수정</h1>

<div class="col-md-12">
    <div class="col-md-4">
        <form>
            <div class="form-group">
                <label for="id">글 번호</label>
                <input type="text" class="form-control" id="id" value="{{posts.id}}" readonly>
            </div>
            <div class="form-group">
                <label for="title">제목</label>
                <input type="text" class="form-control" id="title" value="{{posts.title}}">
            </div>
            <div class="form-group">
                <label for="author">작성자</label>
                <input type="text" class="form-control" id="author" value="{{posts.author}}" readonly>
            </div>
            <div class="form-group">
                <label for="content">내용</label>
                <textarea class="form-control" id="content">{{posts.content}}</textarea>
            </div>
        </form>
        <a href="/" role="button" class="btn btn-secondary">취소</a>
        <button type="button" class="btn btn-primary" id="btn-update">수정 완료</button>
        <button type="button" class="btn btn-danger" id="btn-delete">삭제</button>
    </div>
</div>

{{>layout/footer}}

😀  Service 클래스에 수정 / 삭제 기능을 추가해보자!

수정 기능은 앞전에 만들어 놓았습니다.

@Transactional
public Long update(Long id, PostsUpdateRequestDto requestDto) {
Posts entity = getEntity(id);
    entity.update(requestDto.getTitle(), requestDto.getContent());
    return entity.getId();
}

service 클래스에 삭제 기능을 추가해봅시다!

@Transactional
public void delete(Long id) {
    Posts entity = getEntity(id);
    postsRepository.delete(entity);
}

버튼 기능 중에 수정, 삭제 기능을 만들어야합니다. 아래 js 코드를 추개해줍시다!

varmain={

init: function() {
var _this = this;

        $('#btn-save').on('click', function() {
_this.save();
});

        $('#btn-update').on('click', function() {
_this.update();
});

        $('#btn-delete').on('click', function() {
_this.delete();
});
},

    save: function() {
var data ={
title: $('#title').val(),
            author: $('#author').val(),
            content: $('#content').val()
        };

        $.ajax({
type: 'POST',
            url: '/api/v1/posts',
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            data:JSON.stringify(data)
        }).done(function() {
alert('글이 등록되었습니다.');
window.location.href = '/';
}).fail(function(error) {
alert(JSON.stringify(error));
});
},

    update: function() {
var data ={
title: $('#title').val(),
            content: $('#content').val()
        };

        var id = $('#id').val();

        $.ajax({
type: 'PUT',
            url: '/api/v1/posts/' + id,
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            data:JSON.stringify(data)
        }).done(function() {
alert('글이 수정되었습니다.');
window.location.href = '/';
}).fail(function(error) {
alert(JSON.stringify(error));
});
},

    delete: function() {
var id = $('#id').val();

        $.ajax({
type: 'DELETE',
            url: '/api/v1/posts/' + id,
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
}).done(function() {
alert('글이 삭제되었습니다.');
window.location.href = '/';
}).fail(function(error) {
alert(JSON.stringify(error));
});
}
};

main.init();

😀  Controller 클래스에 수정, 삭제 핸들러를 생성해보자!

수정 핸들러는 미리 만들어 놓은 상태입니다.

@PutMapping("/api/v1/posts/{id}")
public Long update(@PathVariable Long id, @RequestBody PostsUpdateRequestDto requestDto) {
    return postsService.update(id, requestDto);
}

삭제 핸들러를 만들어봅시다.

@DeleteMapping("/api/v1/posts/{id}")
public Long delete(@PathVariable Long id) {
    postsService.delete(id);
    return id;
}

😀  Model의 객체를 수정하는 핸들러를 생성해보자!

@GetMapping("/posts/update/{id}")
public String postsUpdate(@PathVariable Long id, Model model) {
    PostsResponseDto responseDto = postsService.findById(id);
    model.addAttribute("posts", responseDto);
    return "posts-update";
}