[기초 API 구현] - 메인화면 게시글 호출 구현

박성규·2022년 5월 23일
0

[스프링 부트]

목록 보기
11/38
post-thumbnail

db에 값들이 잘 저장되고있으니

그 값들을 바탕으로 main으로 불러보자

1.Controller

 @GetMapping("/")
    public String mainview(Model model){

        List<Posting> posts = postingService.postview();
        model.addAttribute("posts",posts);

        return "main";
    }

2.Service

public List<Posting> postview() {
        return postRepository.findAll();
    }

3.ajax , 타임리프

function postview() {
            $.ajax({
                type: "GET",
                url: '/',
                success: function (response) {
                    window.location.reload()
                }
            })
        }
<div class="mb-2 card" th:each="post : ${posts}">
            <div 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>

4.결과화면

잘 보인다~

컨트롤러가 service의 postView를 호출하면
service는 postRepository에 findAll()을 호출한다.

List로 반환된 값을 컨트롤러 까지 잘 옮겨주고~
model.addAttribute를 통해서 넘겨줬다

0개의 댓글

관련 채용 정보