스프링부트에서 @Controller는 기본적으로 반환값을 이용하여 템플릿을 찾습니다. 이러한 템플릿에서 데이터를 담은 자바객체를 활용하기 위해서는 모델이라는 것이 필요합니다. 즉, 모델은 컨트롤러와 뷰 사이를 오가며 데이터를 전달해주는 역할을 합니다. 이번 포스트에서는 모델을 활용하는 방법에 대해 다루어보도록 하겠습니다.
컨트롤러에 모델 주입
@GetMapping("/question/list")
public String list(Model model) {
List<Question> questionList = this.questionRepository.findAll();
model.addAttribute("questionList", questionList); //questionList 내용을 questionList라는 속성으로 정의
return "question_list";
}
- Model클래스는 파라미터에서 선언만 해주어도 스프링부트에서 자동으로 객체를 생성해줍니다.
- Model의 addAttribute()메서드를 이용하여 속성명과 속성값을 모델에 저장할 수 있습니다.
- 모델에 저장하면 그 값을 템플릿에서도 활용할 수 있습니다.
타임리프에서 활용하기
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>Insert title here</title>
</head>
<body>
<h2>Hello Template</h2>
<table>
<thead>
<tr>
<th>제목</th>
<th>작성일시</th>
</tr>
</thead>
<tbody>
<tr th:each="question : ${questionList}">
<td th:text="${question.subject}"></td>
<td th:text="${question.createDate}"></td>
</tr>
</tbody>
</table>
</body>
</html>
- th: 는 타임리프 문법이다.
- each는 자바의 for-each 구문과 비슷하고, text는 값을 출력한다.
- ${questionList}는 모델에 저장된 값을 의미하고, 이 리스트에서 값을 하나씩 꺼내어 question이라는 변수에 저장한다.
- 참고로 th:text 대신 [[ ]]를 이용할 수 있다.
<!-- Before -->
<tr th:each="question : ${questionList}">
<td th:text="${question.subject}"></td>
<td th:text="${question.createDate}"></td>
</tr>
<!-- After : 이렇게도 가능합니다 -->
<tr th:each="question : ${questionList}">
<td>[[${question.subject}]]</td>
<td>[[${question.createDate}]]</td>
</tr>
참조
'웹개발' 카테고리의 다른 글
서비스(Service) (0) | 2023.08.08 |
---|---|
리다이렉트, 포워드 (0) | 2023.08.08 |
JPA와 H2서버 사용하기 (0) | 2023.06.18 |
컨트롤러 (0) | 2023.06.18 |
스프링부트 프로젝트의 구조 (0) | 2023.06.18 |