발생
게시판 만들기 프로젝트 진행 도중 컨트롤러에서 View를 호출하는 과정에서 발생하였다.
에러로그
Bean property 'id' is not readable or has an invalid getter method
id 필드를 읽을 수 없거나, getter 메서드가 잘못되었다고 한다. 필자의 경우는 id 필드를 읽을 수 없는 경우였다.
해결
PostForm.java
import jakarta.validation.constraints.NotEmpty;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class PostForm {
private Long id; // 추가
@NotEmpty(message = "제목은 필수입니다.")
private String title;
private String content;
}
id 필드를 추가해주었다.
PostController.java
@GetMapping("/boards/{postId}/update")
public String updatePostForm(@PathVariable("postId") Long postId, Model model){
Post findPost = postService.findPostById(postId);
PostForm postForm = new PostForm();
postForm.setId(postId); // 추가
postForm.setTitle(findPost.getTitle());
postForm.setContent(findPost.getContent());
model.addAttribute("postForm", postForm);
return "boards/updatePostForm";
}
postForm에 id를 추가하여 View로 넘겨주었다.
updatePostForm.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="fragments/header :: header" />
<body>
<div class="container">
<div th:replace="fragments/bodyHeader :: bodyHeader"/>
<form th:object="${postForm}" method="post">
<!-- id -->
<input type="hidden" th:field="*{id}" />
<div class="form-group">
<label th:for="title">제목</label>
<input type="text" th:field="*{title}" class="form-control" placeholder="제목을 입력하세요" /> </div>
<div class="form-group">
<label th:for="content">내용</label>
<input type="number" th:field="*{content}" class="form-control" placeholder="내용을 입력하세요" /> </div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<div th:replace="fragments/footer :: footer" />
</div> <!-- /container -->
</body>
</html>
정상 렌더링 되었다.