728x90
반응형
이번 포스팅에서는 게시판에 올린 글을 수정 기능을 구현 할 것이다.
글 수정 기능은 먼저 수정하고 싶은 게시글이 로그인한 사용자가 작성한 게시글인지 본인 확인이 필요하다.
내부단에서 게시글 작성자인지 확인 후 작성자이면 수정을 아니면 에러메세지를 출력할 수 있도록 만들것이다.
1. postupdate.html
글 작성 폼이랑 동일하게 구성했다. 버튼의 하이퍼 링크정도 변경해줬다.
<body>
<div class="container">
<div class="py-5 text-center">
<h2>게시글 수정</h2>
</div>
<form th:action="@{/freeboard/update/{boardId}(boardId=${board})}" th:object="${postDTO}" method="post">
<div>
<label for="title">제목</label>
<input type="text" id="title" th:field="*{title}" class="form-control" th:value="${postDTO.title}" th:errorclass="field-error">
<div class="field-error" th:errors="*{title}" />
</div>
<div class="mb-3">
<label for="content">내용</label>
<textarea class="form-control" rows="5" id="content" name="content" th:text="${postDTO.content}" th:value="*{content}"></textarea>
</div>
<hr class="my-4">
<button class="btn btn-primary btn-lg" type="submit">
수정
</button>
<button class="btn btn-secondary btn-lg" th:onclick="|location.href='@{/freeboard}'|" type="button">
취소
</button>
</form>
</div>
</body>
2. postController.java
현재 로그인 한 사용자와 게시글의 작성자가 다를 때는 게시글을 수정하려면 이전에 썼던 제목과 본문을 불러와야 하기 때문에 해당 게시글의 boardId를 사용해서 게시글의 정보를 불러와 model 객체로 폼에 보내준다.
@GetMapping("/update/{boardId}")
public String GetPostUpdate(@PathVariable("boardId") Long boardId, Model model, Principal principal) {
Post post = postService.findPostDetail(boardId);
Long findSignMemberId = memberServiceImpl.findUsername(principal.getName()).getUserId();
if(findSignMemberId != post.getMember().getUserId()) {
model.addAttribute("msg", "해당 게시글의 작성자가 아닙니다.");
model.addAttribute("url", "/freeboard/detail/"+boardId);
return "alertmessage";
}
PostDTO postDTO = new PostDTO(post.getTitle(), post.getContent());
model.addAttribute("board", boardId);
model.addAttribute("postDTO", postDTO);
return "/board/postupdate";
}
@PostMapping("/update/{boardId}")
public String PostUpdate(@PathVariable("boardId") Long boardId, @Valid @ModelAttribute PostDTO postDTO) {
postService.updatePost(postDTO, boardId);
return "redirect:/freeboard/detail/" + boardId;
}
3. postService.java
@Transactional
public void updatePost(PostDTO postDTO, Long boardId) {
Post post = postRepository.findByBoardId(boardId);
post.update(postDTO.getTitle(), postDTO.getContent());
}
스프링에서 글 수정을 할 때는 JpaRepository로 업데이트를 해주지 않아도 스프링 영속성에 의해 수정이 된다.
따로 나눠서 영속성에 대해 포스팅 할 예정이지만 관련되어있으니 간단하게만 설명해 보자면,
영속성 컨텍스트(Persistence Context)는 엔티티를 영구 저장하는 환경이라는 뜻이다. 서비스 별로 하나의 EntityManager Factory가 생성되며 Database에 접근하는 트랜잭션이 생길 때 마다 쓰레드 별로 Entity Manager를 생성하여 영속성 컨텍스트에 접근을 한다.
글 수정에서는 엔티티의 변경 감지 즉 더티체킹(Dirty Checking)을 해서 영속성 컨텍스트에 따로 알려주지 않아도 알아서 변경사항을 체크한다.
로그인한 유저는 test라는 사용자이고 해당 글에 작성자는 a이다.
이 상태에서 수정버튼을 누르게 되면 로그인 한 사용자가 해당 게시글의 작성자가 아니기 때문에 수정은 당연히 안되고 알람을 띄우게 된다.
글 상세 보기 화면과 다르게 readonly가 풀렸고 수정할 내용을 입력 후 수정 버튼을 누르면 실제로 글 목록에서도 수정된 제목으로 보인다.
DB를 확인 해 보면 2번째 컬럼이 글 작성일 4번째 컬럼이 수정일인데 작성일은 변하지 않고 수정일만 잘 변한 것을 확인할 수 있다.
만들고 싶은 서비스를 스스로 공부하고 만들어 보면서 기록하는 개인 공부 블로그입니다.
내용 중 최적화가 가능한 부분 혹은 궁금한 점은 언제든지 댓글로 남겨주세요🧐
728x90
반응형
'Projects > 식단 짜주는 웹' 카테고리의 다른 글
[Spring/식단 추천 API] 게시판 글 삭제 기능 구현 - 7 (0) | 2023.11.20 |
---|---|
[Spring/식단 추천 API] 게시판 글 상세보기 기능 구현 - 5 (0) | 2023.11.16 |
[Spring/식단 추천 API] 게시판 글 작성 기능 구현 - 4 (1) | 2023.11.16 |
[Spring/식단 추천 API] 게시판 글 목록 페이지 구현 - 3 (0) | 2023.11.16 |
[Spring/식단 추천 API] 로그인 기능 구현 - 2 (1) | 2023.11.11 |