[스프링 부트] 12. 뷰 렌더링

lhs's avatar
Nov 17, 2024
[스프링 부트] 12. 뷰 렌더링
 

1. BoardController

@RequiredArgsConstructor @Controller public class BoardController { private final BoardService boardService; @GetMapping("/") public String list(Model model) { List<Board> boardList = boardService.게시글목록보기(); model.addAttribute("models", boardList); return "list"; } }
  • BoardService게시글목록보기() 메서드를 호출하여 게시글 목록을 가져오고, 이를 boardList에 저장
  • Model model : Model 객체는 디스패처 서블릿에 의해 생성되어 컨트롤러 메서드에 전달되며, 뷰로 전달할 데이터를 저장하는 역할을 한다.
  • model.addAttribute("models", boardList) : Model 객체에 "models"라는 이름으로 boardList를 저장하여, 뷰에서 이를 참조할 수 있도록 전달한다.

2. BoardService

@RequiredArgsConstructor @Service public class BoardService { private final BoardRepository boardRepository; public List<Board> 게시글목록보기() { return boardRepository.findAll(); } }
  • 게시글목록보기() : boardRepositoryfindAll() 메서드를 사용하여 게시글 목록을 반환하는 메서드

3. list.mustache

<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>blog</title> </head> <body> <nav> <ul> <li> <a href="#">홈</a> </li> <li> <a href="#">글쓰기</a> </li> </ul> </nav> <hr> <section> <table border="1"> <tr> <th>번호</th> <th>제목</th> <th></th> </tr> {{#models}} <tr> <td>{{id}}</td> <td>{{title}}</td> <td><a href="/board/{{id}}">상세보기</a></td> </tr> {{/models}} </table> </section> </body> </html>
  • Mustache 문법은 중괄호를 두 개 사용한다.
  • for문은 {{#models}}와 같이 #Model에 저장된 키 값을 사용하여 시작한다.
  • for문을 닫을 때는 {{/models}}와 같이 슬래시를 사용한다.
  • for문 안의 값은 {{id}}{{title}}과 같이 변수 이름을 사용한다.

4. 출력 확인

notion image
Share article

LHS's Study Space