🌱 이번 장의 스터디 범위
- 스프링 부트에서의 화면 처리 방법
- js/css 선언 위치를 다르게 하여 웹사이트의 로딩 속도를 향상하는 방법
- js 객체를 이용하여 브라우저의 전역 변수 충돌 문제를 회피하는 방법
🌱 게시글 삭제 화면 만들기
- posts-update.mustache 코드 추가 : 삭제 버튼을 본문에 추가
// posts-update.mustache
{{>layout/header}}
<h1>게시글 수정</h1>
<div class="col-md-12">
...
<button type="button" class="btn btn-primary" id="btn-update">수정 완료</button>
// btn-danger : 삭제 버튼을 수정 완료 버튼 옆에 추가한 후 해당 버튼 클릭 시 JS에서 이벤트를 수신
<button type="button" class="btn btn-danger" id="btn-delete">삭제</button>
</div>
</div>
{{>layout/footer}}
- index.js 코드 추가 : 삭제 이벤트를 진행할 JS 코드 추가
// index.js
var main = {
init : function () {
...
$('#btn-delete').on('click', function () {
_this.delete();
});
},
save : function () {
...
},
update : function () {
...
},
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();
- PostsService에 코드 추가 : 삭제 API 생성을 위한 서비스 메소드
// PostsService.java
@Transactional
public void delete(Long id) {
Posts posts = postsRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("해당 게시글이 없습니다. id=" + id));
/* JpaRepository에서 지원하는 delete 메소드 활용
엔티티를 파라미터로 삭제할 수도 있고, deleteById 메소드를 이용하면 id로 삭제할 수 있음
존재하는 Posts인지 확인을 위해 엔티티 조회 후 그대로 삭제 */
postsRepository.delete(posts);
}
- PostsApiController에 코드 추가 : 서비스에서 만든 delete 메소드를 컨트롤러가 사용하도록 코드 추가
// PostsApiController.java
@DeleteMapping("/api/v1/posts/{id}")
public Long delete(@PathVariable Long id) {
postsService.delete(id);
return id;
}
- 삭제 버튼을 클릭 해 테스트 수행
- 자동으로 메인 페이지로 이동하면, 기존 게시글이 삭제되었는지 확인
'Java-Spring > 스프링 부트와 AWS로 혼자 구현하는 웹 서비스' 카테고리의 다른 글
[Spring Boot] 05장. 스프링 시큐리티와 OAuth 2.0으로 로그인 기능 구현하기 - 구글 서비스 등록 (0) | 2021.10.29 |
---|---|
[Spring Boot] 05장. 스프링 시큐리티와 OAuth 2.0으로 로그인 기능 구현하기 - 스프링 시큐리티와 스프링 시큐리티 Oauth2 클라이언트 (0) | 2021.10.28 |
[Spring Boot] 04장. 머스테치로 화면 구성하기 - 게시글 수정 화면 만들기 (0) | 2021.10.14 |
[Spring Boot] 04장. 머스테치로 화면 구성하기 - 전체 조회 화면 만들기 (0) | 2021.10.13 |
[Spring Boot] 04장. 머스테치로 화면 구성하기 - 게시글 등록 화면 만들기 (0) | 2021.10.13 |