질문에 답변을 등록하고 보여주는 기능 추가

 

question_detail.html - 답변 등록 버튼 생성

<답변등록> 버튼을 누르면 전송되는 form의 action은 타임리프의 "th:action" 속성으로 생성한다. 

 

UI 가 엉성하지만 후에 부트스트랩을 이용하여 작업할 예정이다.


AnswerController 생성

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;
	
	@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);
		
		// TODO: 답변을 저장한다. 
		
		return String.format("redirect:/question/detail/%s", id);
	}
	

}

 

@PostMapping은 @RequestMapping 과 동일하게 매핑을 담당하는 역할을 하지만 POST요청만 받아들일 경우에 사용한다. 만약 위 URL을 GET방식으로 요청할 경우에는 오류가 발생

@PostMapping(value="/create/{id}") 대신 @PostMapping("/create/{id}") 처럼 value는 생략해도 된다.

 

추가로 " @RequestParam String content" 이 추가되었는데, 이는 템플릿에서 답변으로 입력한 내용을 얻기 위함이다.

템플릿의 답변 내용에 해당하는 textarea의 name 속성명이 content이기 때문에 여기서도 변수명을 content로 사용해야 한다. 만약 content 대신 다른 이름으로 사용하면 오류가 발생할 것이다.

 

//TODO:답변을 저장한다.

 

createAnswer 메서드의 URL 매핑 /create/{id}에서 {id}는 질문의 id 이므로 이 id 값으로 질문을 조회하고 없을 경우에는 404 오류가 발생할 것이다. 하지만 아직 답변을 저장하는 코드를 작성하지 않고 일단 다음과 같은 주석으로 답변을 저장해야 함을 나타내었다.

+ Recent posts