문제 상황
- 글을 수정하면 등록일은 그대로 두고, 수정일만 변경하고 싶은데 자꾸 등록일도 현재 시간으로 변경되었다.
- 이유를 생각해보니 GET에서 form으로 Board 객체를 넘겨주었지만, POST에서 @ModelAttribute로 받는 Board 에는 id, name, title, content 밖에 들어가지 않는다는 걸 깨닳았다.
BoardController
@GetMapping("/updateform")
public String updateForm(@RequestParam(name="id") Long id, Model model) {
Board board = boardService.findBoardById(id);
model.addAttribute("board", board);
return "board/updateForm";
}
@PostMapping("/update")
public String update(@ModelAttribute Board board,
@RequestParam(name="password") String password,
RedirectAttributes redirectAttributes) {
if (boardService.verifyPassword(board.getId(), password)) {
boardService.saveBoard(board);
redirectAttributes.addFlashAttribute("message", "게시글이 정상적으로 수정되었습니다.");
return "redirect:/view?id=" + board.getId();
} else {
redirectAttributes.addFlashAttribute("message", "비밀번호가 일치하지 않습니다.");
return "redirect:/updateform?id=" + board.getId();
}
}
BoardService
@Transactional
public Board saveBoard(Board board) {
if (board.getCreatedAt() == null) { // 게시글 등록일 경우 등록일 지정도 함께
board.setCreatedAt(LocalDateTime.now());
}
board.setUpdatedAt(LocalDateTime.now()); // 수정일 경우는 수정일만 새로 지정
return boardRepository.save(board);
}
해결 방법
- 등록일을 POST로 넘겨주기 위해 input type=hidden 으로 등록일 속성을 넣어주어서 해결했다.
<input type="hidden" id="createdAt" name="createdAt" th:value="${board.createdAt}">
사용 예시
<form th:action="@{/update}" method="post">
<input type="hidden" id="id" name="id" th:value="${board.id}">
<!-- 이 부분을 넣음으로 해결 -->
<input type="hidden" id="createdAt" name="createdAt" th:value="${board.createdAt}">
<label for="name">Name: </label>
<input type="text" id="name" name="name" th:value="${board.name}" readonly>
<label for="title">Title: </label>
<input type="text" id="title" name="title" th:value="${board.title}" required>
<label for="content">Content: </label>
<input type="text" id="content" name="content" th:value="${board.content}" required>
<label for="password">Password (for verification): </label>
<input type="password" id="password" name="password" required>
<input type="submit" value="글 수정">
</form>
'🔫 트러블슈팅' 카테고리의 다른 글
[카카오 지도 API] 같은 장소인데 다른 좌표로 판단하는 부동소수점 오차 문제 (0) | 2024.09.18 |
---|---|
[카카오 지도 API] 마커 인덱스가 index+1 값으로 표시되는 문제 (0) | 2024.09.13 |
[카카오 지도 API] 검색 결과 목록의 페이지별 마커 인덱스 겹침 문제 (0) | 2024.09.13 |
[Spring Boot] BindingResult를 통한 유효성 검증 시 잘못된 BindingResult 위치 (0) | 2024.06.13 |
[HTML] form 태그 외부에서 button submit으로 form 제출하기 (0) | 2024.06.07 |