spring boot #6

·2022년 4월 19일
0

spring

목록 보기
7/22

DB에 저장된 데이터를 웹페이지에서 확인하기

  1. 사용자가 데이터를 조회하기 위해서는 DB의 ID형식으로 url에 입력.

  2. 컨트롤러에 파라미터로 url로 받아올때는 어노테이션이 필요하다.
    @PathVariable

  3. DB에 있는 데이터를 컨트롤러로 가져올땐 Repository를 통해..
    (DB를 entity로..)
    articleRepository.findById(id)
    데이터가 없을 때는 null값을 넣어준다. .orElse(null)

  4. 컨트롤러에서 model에 entity를 등록해야 view에서 사용가능하다.

  5. 뷰 페이지에서는 {{#article}} 영역안에서 article 데이터를 사용할 수 있다.

@GetMapping("/articles/{id}")
    public String show(@PathVariable Long id, Model model){

        log.info("id = "+ id);

        //1. 아이디로 데이터 가져오기
        Article articleEntity =  articleRepository.findById(id).orElse(null);


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


        //3. 보여줄 페이지를 설정
        return "/articles/show";
    }
//show.mustache

{{>layout/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}}

    <tr>
        <th>{{id}}</th>
        <td>{{title}}</td>
        <td>{{content}}</td>
    </tr>

    {{/article}}

    </tbody>
</table>

{{>layout/footer}}

Article.java에 디폴트 생성자가 없어서 오류가 발생할 수도 있다.
어노테이션을 추가하여 해결 가능.
@NoArgsConstructor
//디폴트 생성자를 추가해주는 어노테이션

사진 출처 : https://youtu.be/E0YO0XqpBIY

0개의 댓글