1. 게시글 조회페이지 템플릿 만들기.
resource/template/index.mustache
<!-- //header 파일 가져오기 -->
{{>layout/header}}
    <h1>스프링 부트로 시작하는 웹 서비스</h1>
    <div class ="col-md-12">
        <div class="row">
            <div class = "col-md-6">
                <a href="/posts/save" role="button" class="btn btn-primary">글 등록</a>
            </div>
        </div>
    </div>
    <br>
    <!-- 목록 출력 영역 -->
    <table class = "table table-horizontal table-bordered">
        <thead>
        <tr>
            <th>게시글번호</th>
            <th>제목</th>
            <th>작성자</th>
            <th>최종수정일</th>
        </tr>
        </thead>
        <tbody>
        {{#posts}} <!--posts라는 List를 순회합니다.-->
            <tr>
                <td>{{id}}</td> <!--posts에 돌아가는 객체의 필드를 가져옴-->
                <td>{{title}}</td>
                <td>{{author}}</td>
                <td>{{modifiedDate}}</td>
            </tr>
            {{/posts}}
        </tbody>
    </table>
{{>layout/footer}}{{#posts}}라는 변수가 배열형태면 반복문형태로 <tr>태그를 만든다.
2.controoller에서서 모델타입의 posts라는 객체를 추가해야 한다.
main/java/com/jojoldu.book.springboot/web/dto/indexController
package com.jojoldu.book.springboot.web.dto;
import com.jojoldu.book.springboot.service.posts.PostsService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@RequiredArgsConstructor
@Controller
public class IndexController {
    private final PostsService postsService;
    @GetMapping("/")  //HTTP GET 요청을 특정 핸들러 메소드에 맵핑하기위한 annotation.
    public String index(Model model) {
        model.addAttribute("posts", postsService.findAllDesc()); //posts라는 모델객체로 받아와서 추가.
        return "index";
    }
    @GetMapping("/posts/save")
    public String postsSave() {
        return "posts-save";
    }
}
Model객체에 "posts"와 post. postsService.findAllDesc()에서 받은 데이터를 추가한다.
3. postService에 findAllDesc라는 메서드를 추가한다.
java/com.jojoldu.book.springboot/service/posts/PostsService
package com.jojoldu.book.springboot.service.posts;
import com.jojoldu.book.springboot.domain.posts.Posts;
import com.jojoldu.book.springboot.domain.posts.PostsRepository;
import com.jojoldu.book.springboot.web.dto.PostsListResponseDto;
import com.jojoldu.book.springboot.web.dto.PostsResponseDto;
import com.jojoldu.book.springboot.web.dto.PostsSaveRequestDto;
import com.jojoldu.book.springboot.web.dto.PostsUpdateRequestDto;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.stream.Collectors;
@RequiredArgsConstructor //초기화 되지않은 final 필드나 @notnull이 붙은 필드에 생성자를 생성
@Service
public class PostsService {
    private final PostsRepository postsRepository;
    @Transactional//여러기능을 하나로 묶어 실행해서 하나라도 잘못되면 모두 취소해야한다(데이터 무결성 보장).
    public long save(PostsSaveRequestDto requestDto){
        return postsRepository.save(requestDto.toEntity()).getId();
    }
    @Transactional
    public Long update(Long id, PostsUpdateRequestDto requestDto){
        Posts posts = postsRepository.findById(id).orElseThrow(() ->
                new IllegalArgumentException("해당 게시글이 없습니다. id=" + id));
        posts.update(requestDto.getTitle(), requestDto.getContent());
        return id;
    }
    public PostsResponseDto findById (long id) {
        System.out.print("아이디는" + id);
        Posts entity = postsRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("해당 게시글이 없습니다. id=" + id));
        return new PostsResponseDto(entity);
    }
	
    //리스트형태로 리턴
    @Transactional(readOnly = true)
    public List<PostsListResponseDto> findAllDesc(){
        return postsRepository.findAllDesc().stream()
                .map(PostsListResponseDto::new)
                .collect(Collectors.toList());
    }
}
데이터 교환을 하기위해 PostsListResponseDto를 생성해줘야 한다.
java/com.jojoldu.book.springboot/web/dto/PostsListResponseDto
package com.jojoldu.book.springboot.web.dto;
import com.jojoldu.book.springboot.domain.posts.Posts;
import java.time.LocalDateTime;
public class PostsListResponseDto {
    private long id;
    private String title;
    private String author;
    private LocalDateTime modifiedDate;
    public PostsListResponseDto(Posts entity) {
        this.id = entity.getId();
        this.title = entity.getTitle();
        this.author = entity.getAuthor();
        this.modifiedDate = entity.getModifiedDate();
    }
}
PostsResponse
package com.jojoldu.book.springboot.domain.posts;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
public interface PostsRepository extends JpaRepository<Posts, Long> {
    @Query("SELECT p FROM Posts p ORDER BY p.id DESC") //게시글 데이터를 모두 가져오는 query
    List<Posts> findAllDesc();
}
postRepository.findAllDesc()를 통해서 게시글 데이터를 전부 가져온다.
stream().map(PostsListResponseDto::new).collect으로 postListResponseDto형식 리스트로 리턴시킨다.

'JAVA > Spring Boot' 카테고리의 다른 글
| (Spring Boot) @ResponseBody 동작 원리 (1) | 2021.06.18 | 
|---|---|
| 스프링부트 구글 로그인 환경 설정하기 (0) | 2021.03.31 | 
| (프로젝트 공부)스프링부트를 이용한 게시글 작성. (0) | 2021.03.19 | 
| (프로젝트 진행)mustache레이아웃 나누기. (0) | 2021.03.19 | 
| (프로젝트 진행) mustache를 이용한 기본 페이지 테스트. (0) | 2021.03.17 | 

