hy6
2-10 질문 상세 (실습 기록) 본문
1. 제목 수정하기 : 제목에 링크 추가
- question_list.html
<table>
<thead>
<tr>
<th>제목</th>
<th>작성일시</th>
</tr>
</thead>
<tbody>
<tr th:each="question, index : ${questionList}">
<td>
<a th:href="@{|/question/detail/${question.id}|}" th:text="${question.subject}"></a>
</td>
<td th:text="${question.createDate}"></td>
</tr>
</tbody>
</table>
2. 질문 상세 컨트롤러 만들기
- 이제 localhost:8080에 접속시, 404에러가 뜰 것이다. URL 요청에 대한 매핑이 없기 때문이다. 질문 상세 페이지에 대한 URL 매핑을 QuestionController에 다음과 같이 추가하자.
- QuestionController.java
(... 생략 ...)
import org.springframework.web.bind.annotation.PathVariable;
(... 생략 ...)
public class QuestionController {
(... 생략 ...)
@GetMapping(value = "/question/detail/{id}")
public String detail(Model model, @PathVariable("id") Integer id) {
return "question_detail";
}
}
- 이제 다시 로컬호스트에 접속하면 404에러 대신 500에러가 출력 될 것이다. 이는 응답으로 return할 템플릿이 존재하지 않기 때문이다.
- 다음과 같이 question_detail.html 파일을 신규로 작성하자.
<h1>제목</h1>
<div>내용</div>
- 잘 출력 될 것이다.
3. 서비스
- "제목", "내용" 문자열 대신 데이터의 실제 제목과 내용을 출력하자. QuestionService의 내용을 다음과 같이 수정하자.
- QuestionService.java
(... 생략 ...)
import java.util.Optional;
import com.mysite.sbb.DataNotFoundException;
(... 생략 ...)
public class QuestionService {
(... 생략 ...)
public Question getQuestion(Integer id) {
Optional<Question> question = this.questionRepository.findById(id);
if (question.isPresent()) {
return question.get();
} else {
throw new DataNotFoundException("question not found");
}
}
}
- 포지터리로 얻은 Question 객체는 Optional 객체이기 때문에 위와 같이 isPresent 메서드로 해당 데이터가 존재하는지 검사하는 로직이 필요하다. id 값에 해당하는 Question 데이터가 없을 경우에는 DataNotFoundException을 발생시키도록 해야한다. DataNotFoundException 클래스를 생성하자.
- DataNotFoundException.java
package com.mysite.sbb;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "entity not found")
public class DataNotFoundException extends RuntimeException {
private static final long serialVersionUID = 1L;
public DataNotFoundException(String message) {
super(message);
}
}
- 만약 DataNotFoundException이 발생하면 @ResponseStatus 애너테이션에 의해 404 오류(HttpStatus.NOT_FOUND)가 나타날 것이다.
- QuestionController에서 QuestionService의 getQuestion메서드를 호출하여 Question객체를 템플릿에 전달 할 수 있도록 QuestionController를 다음과 같이 수정한다.
- QuestionController.java
(... 생략 ...)
public class QuestionController {
(... 생략 ...)
@GetMapping(value = "/question/detail/{id}")
public String detail(Model model, @PathVariable("id") Integer id) {
Question question = this.questionService.getQuestion(id);
model.addAttribute("question", question);
return "question_detail";
}
}
4. 템플릿
- QuestionController의 detail 메서드에서 model 객체에 Question객체를 question라는 이름으로 저장했으므로, 다음과 같이 수정이 가능하다.
- question_detail.html.
<h1 th:text="${question.subject}"></h1>
<div th:text="${question.content}"></div>
5. 질문 상세 페이지
'점프 투 스프링 부트' 카테고리의 다른 글
2-12 스태틱 디렉터리와 스타일 시트 (실습 기록) (0) | 2023.10.25 |
---|---|
2-11 답변 등록 (실습 기록) (0) | 2023.10.24 |
2-09 서비스 (실습 기록) (0) | 2023.10.23 |
2-08 ROOT URL (실습 기록) (0) | 2023.10.23 |
2-07 질문 목록과 템플릿 (실습 기록) (0) | 2023.10.21 |