하나씩 차근차근
article thumbnail

이번 포스트에서는 앞에서 만든 질문 상세페이지에서 답변을 등록할 수 있는 기능을 만들어보겠습니다.

 

답변 작성 폼

앞에서 만든 question_detail.html 안에 다음과 같이 답변을 작성하고 등록할 수 있는 폼을 만듭니다.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<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>
</body>
</html>

답변등록 버튼을 누르면 localhost:8080/answer/create/{id} 로 post 방식을 통해

textarea 에 입력된 내용을 content 라는 속성에 담아 전달합니다.

springboot 를 실행시키고 접속을 해보면 다음과 같이 답변 등록 폼이 보입니다.

 

AnswerController 작성

위에서 답변등록을 눌러 localhost:8080/answer/create/{id} 로 post 방식으로 데이터가 전달될때

처리를 할 수 있도록 AnswerController 를 작성하겠습니다.

package com.crud.controller;

import org.springframework.beans.factory.annotation.Autowired;
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.RequestParam;

import com.crud.model.Question;
import com.crud.service.QuestionService;

@Controller
public class AnswerController {
	
	@Autowired
	private QuestionService questionService;

	@PostMapping("/answer/create/{id}")
	public String createAnswer(Model model, @PathVariable("id") Integer id, @RequestParam String content) {
		
		return String.format("redirect:/question/detail/%s", id);
	}
}

위와 같이 createAnswer 메서드를 통해 post 방식으로 content 속성에 담긴 값을 가져옵니다.

이때 @RequestParam 뒤의 변수명은 textarea 의 name 과 동일해야합니다.

 

AnswerService 작성

AnswerService 에서 답변을 저장하는 create 메서드를 추가해보겠습니다.

여기서 추가한 create 메서드를 위에서 작성한 AnswerController 의 createAnswer 메서드에서 사용해서

답변을 데이터베이스에 등록하겠습니다.

package com.crud.service;

import java.time.LocalDateTime;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.crud.model.Answer;
import com.crud.model.Question;
import com.crud.repository.AnswerRepository;

@Service
public class AnswerService {

	@Autowired
	private AnswerRepository answerRepository;
	
	public void create(Question question, String content) {
		Answer answer = new Answer();
		answer.setContent(content);
		answer.setCreateDate(LocalDateTime.now());
		answer.setQuestion(question);
		answerRepository.save(answer);
	}
}

위와 같이 create 메서드는 답변에 content 와 createDate(작성시간),

그리고 어떤 question 에 대한 답변인지 question 을 저장한 answer 객체를 만든 후

AnswerRepository 의 기본 메서드인 save 를 통해 저장합니다.

 

AnswerController 추가

위에서 만든 AnswerSerivce 의 create 메서드를 AnswerController 에 추가해서 사용해봅시다.

package com.crud.controller;

import org.springframework.beans.factory.annotation.Autowired;
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.RequestParam;

import com.crud.model.Question;
import com.crud.service.AnswerService;
import com.crud.service.QuestionService;

@Controller
public class AnswerController {
	
	@Autowired
	private QuestionService questionService;
	
	@Autowired
	private AnswerService answerService;

	@PostMapping("/answer/create/{id}")
	public String createAnswer(Model model, @PathVariable("id") Integer id, @RequestParam String content) {
		
		Question question = questionService.getQuestion(id);
		answerService.create(question, content);
		
		return String.format("redirect:/question/detail/%s", id);
	}
}

AnswerSerivce 를 @Autowired 애너테이션을 통해 등록하였고

createAnswer 메서드 안에서 id 에 해당하는 question 객체를 가져와서 answer 을 등록했습니다.

실제로 답변을 작성하고 등록해보겠습니다.

위와 같이 답변을 작성하고 답변등록 버튼을 클릭합니다.

MariaDB [springboot_crud]> select * from answer;
+----+---------------+---------------------+-------------+
| id | content       | create_date         | question_id |
+----+---------------+---------------------+-------------+
|  1 | this is reply | 2023-01-09 15:31:59 |           1 |
+----+---------------+---------------------+-------------+
1 row in set (0.001 sec)

mysql 을 통해 select * from answer 구문으로 answer 테이블의 데이터를 확인해보면

등록한 답변이 저장된것을 볼 수 있으며, 이때 question_id 는 1 로 저장이 됩니다.

 

답변 표시하기

마지막으로 question_detail 페이지에 답변이 표시되도록 해보겠습니다.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<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>
</body>
</html>

다음과 같이 question_detail.html 에 question.answerList 를 통해 answer 을 가져와 표시합니다.

브라우저로 접속을 해보면 답변이 표시되는것을 볼 수 있습니다.

 

profile

하나씩 차근차근

@jeehwan_lee

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!