@Controller
public class QuestionController {
@RequestMapping("/question/list")
@ResponseBody
public String list(){
return "question_list";
}
}
보통 브라우저에 응답하는 문자열은 return question_list 이런식으로 직접 만들지 않는다.
일반적으로 템플릿 방식으로 작성한다.
이 위치에
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h2>hello </h2>
</body>
</html>
작성한 후
Controller
public class QuestionController {
@RequestMapping("/question/list")
// @ResponseBody
public String list(){
return "question_list";
}
}
@Controller
public class QuestionController {
@Autowired
private final QuestionRepository questionRepository;
public QuestionController(QuestionRepository questionRepository) {
this.questionRepository = questionRepository;
}
@RequestMapping("/question/list")
public String list(Model model){
List<Question> questionList = this.questionRepository.findAll();
model.addAttribute("questionList", questionList);
return "question_list";
}
@Autowired속성 - @Autowired를 적용하여 객체를 주입하는 방식
생성자 - 생성자를 작성하여 객체를 주입하는 방식 (권장하는 방식)
Setter - Setter 메서드를 작성하여 객체를 주입하는 방식 ( 메서드에 @Autowired 애너테이션 적용이 필요)
Question 리포지터의 findAll 메서드를 사용하여 질문목록 데이터인 questionList를 생성하고 Model객체에 "questionList"라는 이름으로 값을 저장했다
Model 객체는 자바클래스와 템플릿간의 연결고리 역할
Model 객체에 값을 담아두면 템플릿에서 그 값을 사용할 수 있다.
( Model 객체는 따로 생성할 필요없이 컨트롤러 메서드의 매개변수로 지정하기만 하면 스프링부트가 자동으로 Model 객체를 생성)
<table xmlns:th="http://www.w3.org/1999/xhtml">
<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>