게시판 만들기(스프링 부트3, 나도코딩 스터디)/5장. 게시글 읽기 : Read
5.3 데이터 목록 조회하기(게시판 만들기 / 길벗 코딩 자율학습단)
coding232624
2023. 11. 24. 18:36
테이터 목록 조회하기(모든 데이터 조회하기)
- URL(/articles)요청을 받기 위해 컨트롤러에 @GetMapping 어노테이션을 선언하기
- 메서드 생성하기(public String index()) / 데이터를 뷰페이지로 전달할 매개변수 model 생성
- 리스트 형의 엔티티 변수(List<Article>)를 생성하고 리파지터리에서 .findAll() 메서드를 통해 모든 데이터 받기
- .findAll()메서드는 Iterable 타입으로 다운캐스팅이 필요(방법은 다음글에 설명)
- 다운 캐스팅을 한 후 model에 .addAttribute()메서드를 통해 데이터 등록
- 뷰페이지(mustache) 반환
- 뷰페이지 작성(단일 데이터 조회때와 동일)
- 그 후 프로그램 재시작 후 데이터 입력 & 조회(http://localhost:8080/articles)
@GetMapping("/articles")
public String index(Model model){
List<Article> articleEntityList = articleRepository.findAll();
model.addAttribute("articleList",articleEntityList);
return "articles/index";
}
{{>layouts/header}}
<table class="table">
<thead>
<tr>
<th scope="col">id</th>
<th scope="col">title</th>
<th scope="col">content</th>
</tr>
</thead>
<tbody>
{{#articleList}}
<tr>
<th>{{id}}</th>
<td>{{title}}</td>
<td>{{content}}</td>
</tr>
{{/articleList}}
</tbody>
</table>
{{>layouts/footer}}

※아래 코드에서 articleList의 정보가 남아있을 경우 <tr>~</tr>부분을 반복함
{{#articleList}}
<tr>
<th>{{id}}</th>
<td>{{title}}</td>
<td>{{content}}</td>
</tr>
{{/articleList}}