스프링부트와 AWS로 혼자 구현하는 웹서비스

12. '게시글 조회' 기능 추가

Mary's log 2024. 10. 20. 18:40

 

 

src/main/resources/templates  -  index.mustache  수정

AS-IS

{{>layout/header}}
    <h1>Starting With Spring Boot Web Service</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>
{{>layout/footer}}

TO-BE

{{>layout/header}}
    <h1>Starting With Spring Boot Web Service</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>
        <br>
        <!--목록 출력 영역-->
        <table class="table table-horizontal table-bordered">
            <thead class="thead-strong">
            <tr>
                <th>게시글 번호</th>
                <th>제목</th>
                <th>작성자</th>
                <th>최종수정일</th>
            </tr>
            </thead>
            <tbody id="tbody">
            {{#posts}}
                <tr>
                    <td>{{id}}</td>
                    <td>{{title}}</td>
                    <td>{{author}}</td>
                    <td>{{modifiedDate}}</td>
                </tr>
            {{/posts}}
            </tbody>
        </table>
    </div>
{{>layout/footer}}

 

 

src/main/java/com/jojoldu/springboot/domain/posts  -  PostsRepository.java  조회 함수 추가

package com.jojoldu.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")
    List<Posts> findAllDesc();
}

 

src/main/java/com/jojoldu/springboot/web/dto  -  PostsListResponseDto.java

package com.jojoldu.springboot.web.dto;

import com.jojoldu.springboot.domain.posts.Posts;
import lombok.Getter;

import java.time.LocalDateTime;

@Getter
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();
    }
}

 

src/main/java/com/jojoldu/springboot/service/posts  -  PostsService.java

package com.jojoldu.springboot.service.posts;

import com.jojoldu.springboot.domain.posts.Posts;
import com.jojoldu.springboot.domain.posts.PostsRepository;
import com.jojoldu.springboot.web.dto.PostsListResponseDto;
import com.jojoldu.springboot.web.dto.PostsResponseDto;
import com.jojoldu.springboot.web.dto.PostsSaveRequestDto;
import com.jojoldu.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
@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;
    }

    @Transactional
    public PostsResponseDto findById(Long 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) // = .map(posts->new PostsListResponseDto(posts))
                .collect(Collectors.toList());
    }
}

 

src/main/java/com/jojoldu/springboot/web  -  IndexController.java   - PostsService를 가져와서 ("/") 주소 소스 변경.

AS-IS

package com.jojoldu.springboot.web;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@RequiredArgsConstructor
@Controller
public class IndexController {

    @GetMapping("/")
    public String index() {
        return "index"; // = [suffix] .mustache
    }

    @GetMapping("/posts/save")
    public String postsSave() {
        return "post-save"; // = [suffix] .mustache
    }
}

TO-BE

package com.jojoldu.springboot.web;

import com.jojoldu.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("/")
    public String index(Model model) {
        model.addAttribute("posts", postsService.findAllDesc());
        return "index"; // = [suffix] .mustache
    }

    @GetMapping("/posts/save")
    public String postsSave() {
        return "post-save"; // = [suffix] .mustache
    }
}

 

 


Application 파일 열기. '현재 파일' 에서 ▷ Run 시작.

크롬 브라우저 주소창   localhost:8080  요청.  (서버를 껐다 키면서 h2가 초기화됐기 때문에, 다시 '게시글 등록'해야함.)