스프링 부트3 제 16장
게시글 밑에 댓글이 없으면 섭하죠?
스프링 부트3 제 16장
뷰 페이지
templates/show.mustache
1
2
3
4
5
<!-- ... 생략 -->
{{>comments/_comments}}
{{>layouts/footer}}
comments/_comments를 입력하여 뷰 파일을 불러온다.
comments/_comments.mustache
1
2
3
4
5
6
7
8
<div>
<!-- 댓글 목록 보기 -->
{{>comments/_list}}
<!-- 새 댓글 작성 하기 -->
{{>comments/_new}}
</div>
다른 뷰 파일들을 불러온다.
comments/_list.mustache
1
2
3
4
5
6
7
8
9
<div>
<!-- 댓글 목록 보기 -->
{{>comments/_list}}
<!-- 새 댓글 작성 하기
{{>comments/_new}}
-->
</div>
comments/_list.mustache
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<div class="card m-2" id="comments-list">
{{#commentDtos}}
<div id="comments-{{id}}" class="card m">
<div class="card-header">
{{nickname}}
</div>
<div class="card-body">
{{body}}
</div>
</div>
{{/commentDtos}}
</div>
{{#commentDtos}} … {{/commentDtos}} 는 commentDtos가 여러 데이터라면 머스테치 문법 안쪽에 있는 내용을 반복하라는 뜻이다.
컨트롤러
ArticleController
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Autowired
private CommentService commentService; // 서비스 객체 주입
// ... 생략
@GetMapping("/articles/{id}")
public String show(@PathVariable Long id, Model model) { // URL 요청으로 들어온 전달값을 매개변수로 받음
// 1. id를 조회해 데이터 가져오기
Article articleEntity = articleRepository.findById(id).orElse(null); // id 값으로 데이터를 찾을 때 해당 값이 없으면 null 반환
List<CommentDto> commentDtos = commentService.comments(id); // 댓글 엔티티를 가져와서 DTO로 변환
model.addAttribute("article", articleEntity);
model.addAttribute("commentDtos", commentDtos);
// 2. 모델에 데이터 등록하기
model.addAttribute("article", articleEntity); // name이란 이름으로 value 객체 추가
// 3. 뷰 페이지 반환하기
return "articles/show";
}
// ... 생략
CommentService 객체 생성 후, 게시글 상세 페이지를 보여줄 때 댓글을 가져와서 모델에 등록하는 코드를 추가했다.
model.addAttribute에서 사용하는 모델은 Spring MVC에서 뷰와 컨트롤러 간의 데이터 전송을 위한 객체로, 뷰에 표시할 데이터를 준비하는 데 사용된된다. 이 모델은 비즈니스 로직을 포함하는 엔티티와는 구별되는 개념이다.
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.