날아라김지원
article thumbnail

- 데이터 조회하기 (웹에서)

1)웹에서 URL요청을 먼저 받기 위해 GetMapping을 추가한다. 주소/articles/id 

그리고 @PathVariable을 통해 URL 변수를 가져온다.

 

2)처리흐름

id로 데이터를 가져온다 -> 가져온 데이터를 모델에 등록한다 -> 그리고 보여줄 페이지를 설정한다. (show.mustache)

ArticleController.java
..........
    
    @GetMapping("/articles/{id}") //변하는 수에 따라 게시글 받아오기
    public String show(@PathVariable Long id, Model model){
        log.info("id = " + id);

        // 1: id로 데이터를 가져옴 Repository가주체이다.
        Article articleEntity = articleRepository.findById(id).orElse(null);
        // orElse부분 : 해당 아이디 값이 없으면 null을 반환해라

        // 2: 가져온 데이터를 모델에 등록!
        model.addAttribute("article",articleEntity);

        // 3: 보여줄 페이지를 설정!

        return "articles/show";
    }
    
    ......

3)보여줄 페이지

아래 파일에서 article모델을 가져올 수 있다.

{{#article}}

~

{{/article}}로 둘러쌓인 곳에서 {{}}를 통해 가져올 수 있다.

show.mustache
{{>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>
    {{#article}}
<!--    이 간격안에서 article모델 가져올 수 있다.-->
    <tr>

        <td>{{id}}</td>
        <td>{{title}}</td>
        <td>{{content}}</td>
    </tr>
    {{/article}}
    </tbody>
</table>

{{>layouts/footer}}

 

원래 아래와같이 Submit한 게시글을 인텔리제이 콘솔에서만 볼 수 있었지만

이와같이 주소/article/id 로가서 웹에서 확인할 수 있다.

 

- 데이터 목록조회 (모든 데이터 전부)

위에와같이 모든 글을 한번에 불러오려고 한다.

 

아래 ArticleController에서 List형태로 다시 설정해준다 이 때 findAll()을 사용해 준다.

ArticleController.java

.......

    @GetMapping("/articles")
    public String index(Model model){
        // 1:모든 Article 가져온다
        List<Article> articleEntityList = articleRepository.findAll();

        // 2:가져온 Article 묶음을 뷰로 전달한다.
        model.addAttribute("articleList",articleEntityList);

        // 3: 뷰 페이지를 설정!

        return "articles/index"; // articles/index.mustache
    }


..

 

ArticleRepository.java

.........

public interface ArticleRepository extends CrudRepository<Article, Long> {
    @Override
    ArrayList<Article> findAll();
}
index.mustache

{{>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}}
<!--        articleList의 내용이 여러개인경우 안의 내용이 반복되서 출력된다.-->
        <tr>

            <td>{{id}}</td>
            <td>{{title}}</td>
            <td>{{content}}</td>
        </tr>
    {{/articleList}}
    </tbody>
</table>

{{>layouts/footer}}

모든걸 정확하게 알고 있지는 않지만 흐름은 보이기 시작한다 Django와 로직은 같다는 느낌도 든다.

 

우선 기능을 크게 구현하고 각 코드들은 좀더 상세하게 살펴 봐야겠다.

 

 

- 참고

스프링 부트, 입문!

https://www.inflearn.com/course/%EA%B0%9C%EB%85%90%EC%8B%A4%EC%8A%B5-%EC%8A%A4%ED%94%84%EB%A7%81%EB%B6%80%ED%8A%B8-%EC%9E%85%EB%AC%B8/dashboard

profile

날아라김지원

@flykimjiwon

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!