홍팍 님의 스프링 부트, 입문! 강의를 보고 작성한 내용이며 이미지 또한 강의에 나오는 이미지를 따라 만들었습니다.
https://www.youtube.com/watch?v=Ym7cAtE2jQs&list=PLyebPLlVYXCiYdYaWRKgCqvnCFrLEANXt&index=29
사용자가 브라우저를 통해 요청
요청 url을 Controller가 받아서 찾고자 하는 데이터의 정보를 Repository에게 전달
Repository는 DB에게 요청해서 데이터를 받아옴
DB는 해당 데이터를 찾아서 Entity로 반환
이 Entity는 Model을 통해 View template로 전달
결과 페이지가 완성되어 클라이언트에게 전달됨
@GetMapping("/articles/{id}") // {id}로 명시하면 이 id는 변하는 값임을 의미
public String show(@PathVariable Long id, Model model) {
log.info("id = " + id);
// 1. id로 DB에서 데이터를 가져옴 (Entity로)
Article articleEntity = articleEntity = articleRepository.findById(id).orElse(null);
// 2. 가져온 데이터를 모델에 등록
model.addAttribute("article", articleEntity);
// 3. 보여줄 페이지를 설정
// articles/show에서 article이라는 Model을 사용 가능
return "articles/show";
}
@GetMapping("/articles/{id}")
: {id}로 명시하면 id는 변하는 값임을 의미
@PathVariable
: 값이 url 주소로부터 입력이 된다는 것을 의미, 파라미터에 작성
데이터를 가져오는 주체 : Repository
findById()
는 CrudRepository가 제공하는 함수
findById()
로 값을 반환할 때, return type은 Optional<Article>
Article articleEntity = articleEntity = articleRepository.findById(id).orElse(null);
id 값을 통해 데이터를 조회
.orElse(null)
: 해당 id값이 없다면 null을 반환
데이터는 Entity 객체에 저장
메소드에 Model을 파라미터로 추가
model.addAttribute()
를 이용해서 Model에 DB에서 받아온 데이터가 저장된 Entity를 등록
<show.mustache> <!-- model에 등록된 데이터는 #attributeName 으로 선언 후 사용 가능 --> {{#article}} <tr> <!-- model에 등록된 데이터 --> <th>{{id}}</th> <td>{{title}}</td> <td>{{content}}</td> </tr> {{/article}}
return "파일명"
@GetMapping("/articles")
public String index(Model model) {
// 1. 모든 Article을 가져온다
ArrayList<Article> articleEntityList = articleRepository.findAll();
// 2. 가져온 Article 리스트를 view로 전달 (Model을 사용)
model.addAttribute("articleList", articleEntityList);
// 3. view 페이지를 설정
return "articles/index";
}
List<Article> articleEntityList = articleRepository.findAll();
DB에서 데이터를 가져오는건 repository가 수행
위의 코드는 에러가 존재
findAll()은 Iterable을 반환하는데 List<Article>
로 받으려고 하기 때문
해결방법
List<Article> articleEntityList = (List<Article>) articleRepository.findAll();
Iterable<Article> articleEntityList = articleRepository.findAll();
@Override ArrayList<Article> findAll();
: ArticleRepository에서 findAll()을 오버라이딩
model.addAttribute("articleList", articleEntityList);
링크와 리다이렉트를 이용해서 페이지들을 연결
Link
편리한 요청이 가능
미리 정해놓은 요청을 간편히 전송하는 것
Redirect
편리한 응답이 가능
클라이언트에게 재요청을 지시
// 새 글 작성 링크 (index.mustache) <a href="/articles/new">New Article</a> // 목록 돌아가기 링크 (new.mustache) <a href="/articles">Back</a> // 리다이렉트 // ArticleController에 새 글 작성 후 데이터조회 페이지로 이동할 수 있도록 지정 // getID()는 Article에 @getter 선언 필요 return "redirect:/articles/" + saved.getId(); // title을 선택했을 때 데이터조회 페이지로 이동 (index.mustache) <td><a href="articles/{{id}}">{{title}}</a></td>
홍팍님 스프링부트3 강의 정말 레전드 같아요