kkkkkkkkkkkk
kkkkk
kkkkkkkkkkkk
전체 방문자
오늘
어제
  • 분류 전체보기
    • CS & OS
    • Algorithms
    • Laguage
    • Book
      • 객체지향의 사실과 오해
      • Effective Java
      • Spring boot 와 AWS로 혼자 구현하는 ..
      • 도메인 주도 계발 시작하기
    • DB
    • Spring
    • Spring Boot
    • JPA
    • Git
    • Clean Code
    • HTTP

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 역할
  • 응집도
  • 객체지향 프로그래밍
  • 결합도
  • 책임
  • 설계 원칙

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
kkkkkkkkkkkk

kkkkk

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

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

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";
}

'Book > Spring boot 와 AWS로 혼자 구현하는 웹서비스' 카테고리의 다른 글

[Book] 18) 스프링 Security와 Oauth2.0으로 로그인 기능 구현하기! -1  (0) 2022.04.03
[Book] 16) 전체 조회 화면 및 기능을 만들어보자!  (0) 2022.04.02
[Book] 15) 머스테치로 화면 구성을 해보자! -2  (0) 2022.04.01
[Book] 14) 머스테치로 화면 구성을 해보자! -1  (0) 2022.04.01
[Book] 13) JPA Auditing으로 생성시간/수정시간 자동화 하기!  (0) 2022.04.01
[Book] 12) H2 DB 웹 콘솔에서 직접 접근해보자!  (0) 2022.04.01
[Book] 11) API 만들어보기! -4  (0) 2022.03.31
[Book] 10) API 만들어보기! -3  (0) 2022.03.31
    'Book/Spring boot 와 AWS로 혼자 구현하는 웹서비스' 카테고리의 다른 글
    • [Book] 18) 스프링 Security와 Oauth2.0으로 로그인 기능 구현하기! -1
    • [Book] 16) 전체 조회 화면 및 기능을 만들어보자!
    • [Book] 15) 머스테치로 화면 구성을 해보자! -2
    • [Book] 14) 머스테치로 화면 구성을 해보자! -1
    kkkkkkkkkkkk
    kkkkkkkkkkkk

    티스토리툴바