1. 데이터 조회 과정
웹 페이지에서 게시글을 등록하면 서버를 통해 DB에 저장된다. DB에 저장된 데이터는 다음과 같은 과정을 거쳐 웹 페이지에서 조회할 수 있다.
① 사용자가 웹 페이지에서 데이터를 조회해 달라고 URL 요청을 보낸다.
② 서버의 컨트롤러가 이 요청을 받아 해당 URL을 찾으려는 데이터 정보(여기서는 id)를 레파지토리에 전달한다.
③ 레파지토리는 정보(id)를 가지고 DB에 데이터 조회를 요청한다.
④ DB는 해당 데이터를 찾아 이를 엔티티로 반환한다.
⑤ 반환된 엔티티는 모델을 통해 뷰 템플릿으로 전달된다.
⑥ 최종적으로 결과 뷰 페이지가 완성돼 사용자 화면에 출력된다.
2. @PathVariable
URL 요청으로 들어온 전달값을 컨트롤러의 매개변수로 가져오는 어노테이션이다.
3. findById()
JPA의 CrudRepository가 제공하는 메서드로, 특정 엔티티의 id 값을 기준으로 데이터를 찾아 Opional 타입으로 반환한다.
4. findAll()
JPA의 CrudRepository가 제공하는 메서드로, 특정 엔티티를 모두 가져와 Iterable 타입으로 반환한다.
5. {{#article}} {{/article}}
뷰. 페이지에서 모델에 등록된 article의 사용 범위를 지정할 때 사용하는 머스테치 문법이다. {{#article}}에서 {{/article}}까지의 범위 내에서 article 데이터를 사용할 수 있다. 등록된 데이터가 복수이면 해당 범위 코드가 반복된다.
6. 반환 데이터 타입 불일치 문제 해결 방법
특정 메서드가 반환하는 데이터 타입과 사용자가 작성한 반환 데이터 타입이 다를 경우, 3가지 방법으로 해결할 수 있다.
① 메서드가 반환하는 데이터 타입을 사용자가 작성한 데이터 타입으로 캐스팅(형변환)하기
② 사용자가 작성한 데이터 타입을 메서드가 반환하는 데이터 타입으로 수정하기
③ 메서드의 반환 데이터 타입을 원하는 타입으로 오버라이딩하기
ArticleController
package com.example.firstproject.controller;
import com.example.firstproject.dto.ArticleForm;
import com.example.firstproject.entity.Article;
import com.example.firstproject.repository.ArticleRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import java.util.ArrayList;
@Slf4j // 로깅 기능을 위한 어노테이션 추가
@Controller
public class ArticleController {
@Autowired
private ArticleRepository articleRepository;
@GetMapping("/new")
public String newArticleController() {
System.out.println("여기와나");
return "/articles/new";
}
@PostMapping("/create")
public String createArticle(ArticleForm form) {
// System.out.println(form.toString());
log.info(form.toString());
// 1. DTO를 엔티티로 변환
Article article = form.toEntity();
// System.out.println(article.toString());
log.info(article.toString());
// 2. 레파지토리로 엔티티를 DB에 저장
Article saved = articleRepository.save(article);
// System.out.println(saved.toString());
log.info(saved.toString());
return "";
}
@GetMapping("/articles/{id}")
public String show(@PathVariable(name = "id") Long id, Model model) {
log.info("id : " + id);
// 1. id를 조회해 데이터 가져오기
Article articleEntity = articleRepository.findById(id).orElse(null);
// 2. 모델에 데이터 등록하기
model.addAttribute("article", articleEntity);
// 3. 뷰 페이지 반환하기
return "/articles/show";
}
@GetMapping("/articles")
public String index(Model model){
// 1. 모든 데이터 가져오기
ArrayList<Article> articleEntityList = articleRepository.findAll();
// 2. 모델에 데이터 등록하기
model.addAttribute("articleList", articleEntityList);
// 3. 뷰 페이지 설정
return "articles/index";
}
}
!! 오류노트 !!
@GetMapping("/articles/{id}")
public String show(@PathVariable(name = "id") Long id, Model model) {
log.info("id : " + id);
// 1. id를 조회해 데이터 가져오기
Article articleEntity = articleRepository.findById(id).orElse(null);
// 2. 모델에 데이터 등록하기
model.addAttribute("article", articleEntity);
// 3. 뷰 페이지 반환하기
return "/articles/show";
}
어제 @Pathvariable Long id라고만 명시하니 id를 찾을 수 없어서 자꾸 오류가 뜸
2시간 가량 찾아보니 (name = "id")라고 뭘 뜻하는 애인지 적어주니 오류 해결 젠장
index.mustache
{{>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}}
<tr>
<th>{{id}}</th>
<td>{{title}}</td>
<td>{{content}}</td>
</tr>
{{/articleList}}
</tbody>
</table>
{{>footer}}
ArticleRepository
package com.example.firstproject.repository;
import com.example.firstproject.entity.Article;
import org.springframework.data.repository.CrudRepository;
import java.util.ArrayList;
public interface ArticleRepository extends CrudRepository<Article, Long> {
@Override
ArrayList<Article> findAll();
}
결과
'복습 및 이해 > 게시판CRUD 복습' 카테고리의 다른 글
게시글 수정하기 : Update (1) | 2025.01.18 |
---|---|
게시판 내 페이지 이동하기 (2) | 2025.01.17 |
롬복과 리팩토링 (4) | 2025.01.16 |
게시판 만들고 새 글 작성하기 : Create (0) | 2025.01.16 |
MVC 패턴 이해와 실습 (0) | 2025.01.15 |