1.js 클릭이벤트 생성
unction detailview(id) {
$.ajax({
type: "GET",
url: '/post/detail?id='+id,
success: function (response) {
}
})
}
<div class="mb-2 card" th:each="post : ${posts}">
<div th:attr="onclick=|detailview('${post.id}')|" class="card-body">
<blockquote class="blockquote mb-0">
<p th:text = "${post.title}"></p>
<footer class="blockquote-footer" th:text = "${post.username}"></footer>
</blockquote>
</div>
</div>
2.Controller
@GetMapping("/post/detail")
public String detailview(@RequestParam Long id, Model model){
model.addAttribute("list",postingService.getdetail(id));
return "detail";
}
3.Service
public Posting getdetail(Long id) {
Optional<Posting> result = postRepository.findById(id);
return result.get();
}
th문법으로 각 div마다 detailview가 담기도록 했다.
이후 컨트롤러, 서비스에서 요청받은 id값으로 db에 조회를 했다.
트러블슈팅
service에서 findById메소드를 사용하면 Optional 타입으로 반환된다.
해당 타입은 null을 포함할 수 있는 객체이기 때문에 변수 선언 후 get()메서드로 값에 직접 접근했다.