<form th:action="@{|/answer/create/${question.id}|}" method="post">
<textarea name="content" id="content" rows="15"></textarea>
<input type="submit" value="답변등록">
</form>
[답변 등록] 버튼을 누르면 /aswer/create/{id} 로 넘어간다
POST 방식으로 /answer/create/{id} URL 호출
POST 방식 = 데이터를 저장하는 용도
@RequestMapping("/answer")
@RequiredArgsConstructor
@Controller
public class AnswerController {
private QuestionService questionService;
@PostMapping("/create/{id}")
public String createAnswer(Model model, @PathVariable("id") Integer id,
@RequestParam(value = "content") String content) {
Question question = this.questionService.getQuestion(id);
// TODO : 답변 저장
return String.format("redirect:/question/detail/%s", id);
}
}
@RequestMapping("/answer") 로 중복되는 도메인 정리
@RequiredArgsConstructor 생성자 자동으로 주입
@Controller 컨트롤러 지정
QuestionService 부른 이유 : question id 불러오려고
@PostMapping 으로 답변 저장
createAnswer 메서드 호출 @PostMapping 으로 매핑
createAnswer 메서드의 매개변수에 @RequestParam(value = "content") String content
앞서 작성한 템플릿에서 답변으로 입력한 내용 (content) 을 얻으려고 추가한 것
<textarea> 의 name 속성명 = content 이기 때문에 변수명을 content 로 사용한 것
/create/{id} 에서 {id} 는 질문 엔티티의 id
이 id 값으로 질문을 조회하고 값이 없을 경우 404 오류가 발생할 것
// TODO : 개발자들이 코드 내에서 아직 해결되지 않은 문제나
추가로 작업해야 하는 부분을 표시 말 그대로To do할 일을 의미
@Service
@RequiredArgsConstructor
public class AnswerService {
private final AnswerRepository answerRepository;
public void create(Question question, String content) {
Answer answer = new Answer();
answer.setContent(content);
answer.setCreateDate(LocalDateTime.now());
answer.setQuestion(question);
this.answerRepository.save(answer);
}
}
답변을 생성하기 위해 create 메서드 추가
create 메서드는 입력받은 2개의 매개변수인 question , content 를 사용해
answer 객체를 생성하여 저장
private final AnswerService answerService;
this.answerService.create(question, content);
AnswerService 추가하고 TODO 자리에 this.answerService.create 추가하기
<h5 th:text="|${#lists.size(question.answerList)}개의 답변이 있습니다.|"></h5>
<div>
<ul>
<li th:each="answer : ${question.answerList}" th:text="${answer.content}"></li>
</ul>
</div>
div와 form 사이에 추가하기