Jump to Spring Boot - 3

현곤·2024년 12월 27일

답변 기능 구현

2-12 question_detail form

<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 방식 = 데이터를 저장하는 용도

2-12 AnswerController

@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 할 일을 의미

2-12 답변 서비스

@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 객체를 생성하여 저장

2-12 컨트롤러에 서비스 추가

private final AnswerService answerService;
this.answerService.create(question, content);

AnswerService 추가하고 TODO 자리에 this.answerService.create 추가하기

2-12 detail.html 답변 표시

<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 사이에 추가하기

profile
코딩하는 곤쪽이

0개의 댓글