Python/Flask

(프로젝트 진행)스프링부트로 게시글 수정.

ri5 2021. 3. 28. 19:17

1.게시글 수정페이지 템플릿 추가.

post-update.mustache

{{>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="{{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" value="{{post.content}}"></textarea>
            </div>
        </form>
        <a href="/" role="button" class="btn btn-secondary" id="btn-cancel">취소</a>

        <button type="button" class="btn btn-primary" id="btn-update">수정완료</button>
    </div>
</div>

{{>layout/footer}}

2. 이벤트 핸들러 추가.

index.js

let main = {
    init : function () {
        let _this = this; //main{}

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

        $('#btn-update').on('click', function (){
            alert("test");
            _this.update();
        });
    },
    save : function () {

        //html 에서 데이터를 가져옴
        let data = {
            title: $('#title').val(),
            author: $('#author').val(),
            content: $('#content').val()
        };

        // 브라우저에서 지원하는 비동기적인 통신방법
        $.ajax({
          type: 'POST', //전송방식
          url: '/api/v1/posts', //호출 url
          dataType: 'json', //전송받는 data type
          contentType:'application/json; charset=utf-8', //서버에서 데이터를 보낼때 보내는 타입
          data: JSON.stringify(data)//게시글에 들어갈 데이터 JSON.stringify()로 문자열로 변형시킴.
        }).done(function (){
            alert('글이 등록되었습니다'); //성공시 띄워줄 알림창
            window.location.href = '/'; //다시 홈페이지로 이동
        }).fail(function (error) {
            alert(JSON.stringify(error)); //실패시 실패이유를 알림창으로 띄워줌
        });

        console.log(data);
    },
    update : function () {

        let data = {
            title: $('#title').val(),
            content: $('#content').val()
        }

        let 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();

update()를 통해 json형식으로 데이터를 보내고 수정요청을 한다.

 

3. 이벤트 핸들러 동작 방식

/api/v1/posts/id값 요청된 url 실행

package com.jojoldu.book.springboot.web;

import com.jojoldu.book.springboot.service.posts.PostsService;
import com.jojoldu.book.springboot.web.dto.PostsResponseDto;
import com.jojoldu.book.springboot.web.dto.PostsSaveRequestDto;
import com.jojoldu.book.springboot.web.dto.PostsUpdateRequestDto;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

@RequiredArgsConstructor //초기화 되지않은 final 필드나 @notnull이 붙은 필드에 생성자를 생성
@RestController //Json 형태로 객체 데이터를 반환하기위한 컨트롤러
public class PostApiController {
    private final PostsService postsService;

    @PostMapping("/api/v1/posts") // @RequestBody 어노테이션을 이용하면 HTTP 요청 Body를 자바 객체로 저장.
    public long save(@RequestBody PostsSaveRequestDto requestDto){
        return postsService.save(requestDto);
    }

    @PutMapping("/api/v1/posts/{id}") //기존의 Mapping 정보를 수정하는데 사용.
    public long update(@PathVariable Long id, @RequestBody PostsUpdateRequestDto requestDto){
        return postsService.update(id, requestDto);
    }

    @GetMapping("/api/v1/posts/{id}") //특정 핸들링 메서드에 매핑하기위하
    public PostsResponseDto findById(@PathVariable Long id){
        return postsService.findById(id);
    }
}

PostService

package com.jojoldu.book.springboot.service.posts;

import com.jojoldu.book.springboot.domain.posts.Posts;
import com.jojoldu.book.springboot.domain.posts.PostsRepository;
import com.jojoldu.book.springboot.web.dto.PostsListResponseDto;
import com.jojoldu.book.springboot.web.dto.PostsResponseDto;
import com.jojoldu.book.springboot.web.dto.PostsSaveRequestDto;
import com.jojoldu.book.springboot.web.dto.PostsUpdateRequestDto;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@RequiredArgsConstructor //초기화 되지않은 final 필드나 @notnull이 붙은 필드에 생성자를 생성
@Service
public class PostsService {
    private final PostsRepository postsRepository;

    @Transactional//여러기능을 하나로 묶어 실행해서 하나라도 잘못되면 모두 취소해야한다(데이터 무결성 보장).
    public long save(PostsSaveRequestDto requestDto){
        return postsRepository.save(requestDto.toEntity()).getId();
    }

    @Transactional
    public Long update(Long id, PostsUpdateRequestDto requestDto){
        Posts posts = postsRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("해당 게시글이 없습니다. id=" + id));
        posts.update(requestDto.getTitle(), requestDto.getContent());

        return id;
    }

    public PostsResponseDto findById (long id) {
        System.out.print("아이디는" + id);
        Posts entity = postsRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("해당 게시글이 없습니다. id=" + id));

        return new PostsResponseDto(entity);
    }

    @Transactional(readOnly = true)
    public List<PostsListResponseDto> findAllDesc(){
        return postsRepository.findAllDesc().stream()
                .map(PostsListResponseDto::new)
                .collect(Collectors.toList());
    }
}

postService를 통해 post클래스를 가져와 해당 아이디가 존재하면 업데이트 시킨다