게시물 수정하기는 삭제하기와 다르게 수정 버튼을 누르면 내용을 수정한 후 수정 내용을 서버로 보내는 과정이 추가된다.

수정 흐름

  1. 사용자가 수정 버튼 클릭
  2. PostsControllereditForm 메서드 (GET /posts/{id}/edit) 호출
  3. editForm 메서드 동작
  4. Service 계층의 findForEdit 메서드
    1. findByIdWithUser(postId) 호출 → Post + User를 fetch join으로 조회
    2. 게시글이 없으면 PostNotFoundException 발생
    3. 작성자 불일치 시 PostAccessDeniedException 발생
    4. 검증 통과 시 PostEditFormResponseDto(postId, title, content, category) 반환
  5. Controller에서 반환된 DTO를 model에 담아 write.html 반환
  6. 사용자가 수정 완료 후 수정 버튼 클릭
  7. PostsControllerupdate 메서드 (PATCH /posts/{id}) 호출
  8. update 메서드 동작
  9. Service 계층의 update 메서드
    1. findByIdWithUser(postId) 호출 → Post + User 조회
    2. 게시글이 없으면 PostNotFoundException 발생
    3. 작성자 검증 실패 시 PostAccessDeniedException 발생
    4. 검증 통과 시 JPA Entity Tracking을 활용하여 엔티티 수정 (setTitle, setContent, setCategory)
  10. Controller에서 수정 완료 후 "redirect:/posts/{postId}" 로 리다이렉트

post-detail.html

<!--수정 버튼 (작성자만 보이게)-->
        <div th:if="${session.user !=null and session.user.id == post.userId}">
            <a th:href="@{/posts/{id}/edit(id=${post.postId})}" class="write-btn">수정하기</a>
        </div>

PostsController editForm 메서드

@GetMapping("/{id}/edit")
    public String editForm(@PathVariable Long id, @SessionAttribute("user") SessionUser sessionUser, Model model){
        PostEditFormResponseDto post = postsService.findForEdit(id, sessionUser.getId());
        model.addAttribute("mode","edit");
        model.addAttribute("post",post);
        return "write";
    }