Notice
Recent Posts
Recent Comments
Link
«   2025/06   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Tags
more
Archives
Today
Total
관리 메뉴

hy6

2-11 답변 등록 (실습 기록) 본문

점프 투 스프링 부트

2-11 답변 등록 (실습 기록)

rantinum 2023. 10. 24. 13:11

1. 답변 등록 버튼 만들기

  • 답변 저장을 위한 form, textarea, input 엘리먼트를 추가한다.
  • question_detail.html
<h1 th:text="${question.subject}"></h1>
<div th:text="${question.content}"></div>
<form th:action="@{|/answer/create/${question.id}|}" method="post">
    <textarea name="content" id="content" rows="15"></textarea>
    <input type="submit" value="답변등록">
</form>
  • 적용 할 경우, 다음과 같은 화면이 출력 될 것이다.

  • 그러나, 만약 여기서 답변을 입력하고 등록 버튼을 누르게 된다면 404에러 메세지가 출력 될 것이다. 해당 오류는 답변 컨트롤러를 만든 후에 URL에 대한 매핑을 처리해야 한다.

2. 답변 컨트롤러 만들기

  • AnswerController.java
package com.mysite.sbb.answer;
import com.mysite.sbb.question.Question;
import com.mysite.sbb.question.QuestionService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@RequestMapping("/answer")
@RequiredArgsConstructor
@Controller
public class AnswerController {
    private final QuestionService questionService;
    @PostMapping("/create/{id}")
    public String createAnswer(Model model, @PathVariable("id") Integer id, @RequestParam String content) {
        Question question = this.questionService.getQuestion(id);
        // TODO: 답변을 저장한다. 
        return String.format("redirect:/question/detail/%s", id);
    }
}

3. 질문 상세 페이지에 답변 표시하기

  • 답변은 등록된 질문 밑에 보여져야 하므로 질문 상세 템플릿에 다음과 같이 수정을 거치도록 한다.
  • question_detail.html
<h1 th:text="${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" rows="15"></textarea>
    <input type="submit" value="답변등록">
</form>
  • 달라진 점 : 기존 코드에서 답변을 확인 할 수 있는 코드를 추가함.
  • #lists.size(question.answerList)}는 답변개수를 의미한다.
  • #lists.size(이터러블객체)는 타임리프가 제공하는 유틸리티인데, 객체의 길이를 반환한다.
  • 답변은 question 객체의 answerList를 순회하여 "li" 엘리먼트로 표시한다.