스프링부트와 AWS로 혼자 구현하는 웹서비스

13. '게시글 수정' 기능 추가

Mary's log 2024. 10. 20. 19:26

 

src/main/java/com/jojoldu/springboot/web  - PostsApiController.java 

전에 만들어둔 @PutMapping("/api/v1/posts/{id}")  이 주소를 이제 사용할 거임.

 

 

src/main/resources/templates  - posts-update.mustache  생성

{{>layout/header}}

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

<div class="col-md-12">
    <div class="col-md-4">
        <form>
            <div class="form-group">
                <label for="title">글 번호</label>
                <input type="text" class="form-control" id="id" value="{{post.id}}" readonly>
            </div>
            <div class="form-group">
                <label for="title">제목</label>
                <input type="text" class="form-control" id="title" value="{{post.title}}">
            </div>
            <div class="form-group">
                <label for="author"> 작성자 </label>
                <input type="text" class="form-control" id="author" value="{{post.author}}" readonly>
            </div>
            <div class="form-group">
                <label for="content"> 내용 </label>
                <textarea class="form-control" id="content">{{post.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}}

정적인 post-update.mustach를 동적으로 움직여서 수정할 수 있는 update ajax를 index.js에 추가

src/main/resources/static/js/app  -  index.js

var main = {
    init : function () {
        var _this = this;
        $('#btn-save').on('click', function () {
            _this.save();
        });
        $('#btn-update').on('click', function () {
            _this.update();
        });
    },
    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));
        });
    },
};

main.init();

 

수정하는 post-update.mustache 화면으로 이동할 수 있게 index.mustache의 제목에 링크를 걸기.

src/main/resources/templates  - index.mustache

{{>layout/header}}
<h1>Starting With Spring Boot Web Service</h1>
<div class="col-md-12">
    <div class="row">
        <div class="col-md-6">
            <a href="/posts/save" role="button" class="btn btn-primary">글 등록</a>
        </div>
    </div>
    <br>
    <!--목록 출력 영역-->
    <table class="table table-horizontal table-bordered">
        <thead class="thead-strong">
        <tr>
            <th>게시글 번호</th>
            <th>제목</th>
            <th>작성자</th>
            <th>최종수정일</th>
        </tr>
        </thead>
        <tbody id="tbody">
        {{#posts}}
            <tr>
                <td>{{id}}</td>
                <td><a href="/posts/update/{{id}}">{{title}}</a></td>
                <td>{{author}}</td>
                <td>{{modifiedDate}}</td>
            </tr>
        {{/posts}}
        </tbody>
    </table>
</div>
{{>layout/footer}}

 

index.js ajax에서 update하면 서버에서 동작할 소스 생성.

 

src/main/java/com/jojoldu/springboot/web  -  IndexController.java

package com.jojoldu.springboot.web;

import com.jojoldu.springboot.service.posts.PostsService;
import com.jojoldu.springboot.web.dto.PostsResponseDto;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@RequiredArgsConstructor
@Controller
public class IndexController {

    private  final PostsService postsService;

    @GetMapping("/")
    public String index(Model model) {
        model.addAttribute("posts", postsService.findAllDesc());
        return "index"; // = [suffix] .mustache
    }

    @GetMapping("/posts/save")
    public String postsSave() {
        return "post-save"; // = [suffix] .mustache
    }

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

        return "posts-update";
    }
}

 

 

Application 파일 열기. '현재 파일' 에서 ▷ Run 시작.

크롬 브라우저 주소창   localhost:8080  요청.  (서버를 껐다 키면서 h2가 초기화됐기 때문에, 다시 '게시글 등록'해야함.)

제목이 누를 수 있게 '파랑색'으로 보임. 누르면

'게시글 수정' posts-update.mustache 화면으로 이동.

미리 '삭제' button 소스를 넣은 스크린샷이니, 아직 안 적었다면 안 뜨는게 맞음.

 

제목, 내용 수정 후, '수정 완료' 버튼 누르기.

미리 '삭제' button 소스를 넣은 스크린샷이니, 아직 안 적었다면 안 뜨는게 맞음.

 

 

 

alert의  '확인'을 누르면    

미리 '삭제' button 소스를 넣은 스크린샷이니, 아직 안 적었다면 안 뜨는게 맞음.

window.location.href = '/';    =    @GetMapping("/")  다시 목록을 조회함.

 

 

 

수정된 데이터로 재조회 됨.