🍊 미션 :
질문 목록의 제목을 클릭 시, 상세 페이지가 출력되도록 구현해주세요.
-그럴 일 없겠지만, 백엔드 단에서는 예외 처리까지 모두 구현해줘야 합니다.(질문 제목 클릭했는데, 질문이 없는 경우)
// QuestionController
@GetMapping("/question/detail/{questionId}")
public String showDetail(@PathVariable("questionId") Long id, Model model) {
Question question = questionService.findById(id);
model.addAttribute("question", question);
return "/question/question_detail";
}
// QuestionService
public Question findById(Long id) {
Optional<Question> oQuestion = questionRepository.findById(id);
if(oQuestion.isPresent()) {
return oQuestion.get();
} else {
throw new QuestionNotFoundException("찾는 질문이 없습니다!");
}
}
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "entity not found")
public class QuestionNotFoundException extends RuntimeException {
public QuestionNotFoundException(String message) {
super(message);
}
}
// question_list.html 에 링크 추가
<tbody>
<tr th:each="question : ${questions}">
<td>
<a th:href="@{|/question/detail/${question.id}|}" th:text="${question.subject}"></a>
</td>
<td th:text="${question.create_date}"></td>
</tr>
</tbody>
// question_detail.html
<body>
<h1>[[${question.subject}]]</h1>
<div th:text = "${question.content}"></div>
</body>
@RequestMapping
🍏 미션 :
질문 상세 템플릿에 form, textarea, input 을 추가해 답변을 등록하는 페이지를 만들어보자.
-답변 등록 버튼을 누르면, 해당 답변이 등록된 후 질문 상세 페이지로 다시 돌아와야 한다.
-질문 상세 페이지에 답변을 표시해보자. (N개의 답변이 있습니다. → 이후 답변들이 보여야 한다.)
@PostMapping("/answer/create/{questionId}")
public String createAnswer(@PathVariable Long questionId, @ModelAttribute("form") AnswerDtoForm form, @RequestParam String content) {
Question question = questionService.findById(questionId);
form.setQuestion(question);
answerServicee.saveAnswer(form);
return "redirect:/question/detail/{questionId}";
}
// AnswerService
public Long saveAnswer(AnswerDtoForm form) {
Answer answer = Answer.builder()
.content(form.getContent())
.question(form.getQuestion())
.build();
answerRepository.save(answer);
return answer.getId();
}
// question_detail.html
<h1>[[${question.subject}]]</h1>
<div th:text = "${question.content}"></div>
<h5 th:text="|${#lists.size(question.answerList)}개의 답변이 있습니다.|"></h5>
<div>
<ul>
<li th:each="answer : ${question.answerList}" th:text="${answer.content}"></li>
</ul>
</div>
<form th:action="@{|/answer/create/${question.id}|}" method="post">
<textarea name="content" id="content" cols="30" rows="15"></textarea>
<input type="submit" value="등록하기">
</form>