답변 저장하기

 

AnswerService.java

package com.myspringboot.ssh.answer;

import java.time.LocalDateTime;

import org.springframework.stereotype.Service;

import com.myspringboot.ssh.question.Question;

import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
@Service
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);
	}

}

AnswerController.java

package com.myspringboot.ssh.answer;

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;

import com.myspringboot.ssh.question.Question;
import com.myspringboot.ssh.question.QuestionService; //추가

import lombok.RequiredArgsConstructor;

@RequestMapping("/answer")
@RequiredArgsConstructor
@Controller
public class AnswerController {
	
	private final QuestionService questionService;
	private final AnswerService answerService;
	
	@PostMapping("/create/{id}") // "/answer/create/{id}"와 같은 URL 요청시 createAnswer 메서드가 호출되도록 함
	public String createAnswer(Model model, @PathVariable("id") Integer id, @RequestParam String content) {
		
		Question question = this.questionService.getQuestion(id);
		
		this.answerService.create(question, content); //추가
		
		return String.format("redirect:/question/detail/%s", id);
	}
	

}

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

 

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는 타임리프가 제공하는 유틸리티로 객체의 길이를 반환한다.

때문에 ${#lists.size(question.answerList)}는 답변이 개수를 의미한다.

 

 

실행결과

 

 

출처 : 점프 투 스프링부트 https://wikidocs.net/161357

+ Recent posts