๐โ๏ธ QNA ์๋น์ค ๊ธฐ๋ฅ ๊ตฌํ (๋ณต์ต) _ 114๊ฐ ~ 118๊ฐ
1๏ธโฃ ์ง๋ฌธ ํผ
โ ๋งํฌ ์ฐ๊ฒฐ์์ ์ผ๋ฐ์ ์ธ url ํํ์ด ์๋ @{ } ํํ์ด ํ์ํ ์ด์ : ๋ฒ์ฉ์ฑ์ ์ํด
2๏ธโฃ ์ง๋ฌธ ์ ์ฅ (Controller ์์ DTO ์ฌ์ฉ)
โ RequestQuestionForm DTO ์์ฑ
public class QuestionDto {
@Getter
@Setter
public static class RequestQuestionForm {
private String subject;
private String content;
}
}
โก Controller ์์ View ๋ก๋ถํฐ ๋๊ฒจ๋ฐ๋๋ก
@Controller
@RequestMapping("/question")
@RequiredArgsConstructor
public class QuestionController {
// (์๋ต)
// ์ง๋ฌธ ๋ฑ๋ก (POST)
@PostMapping("/create")
@ResponseBody
public String createQuestion(QuestionDto.RequestQuestionForm requestQuestionForm) {
return "%s %s".formatted(requestQuestionForm.getSubject(), requestQuestionForm.getContent());
}
}

public class QuestionController {
// (์๋ต)
@PostMapping("/create") // ์๋น์ค์ ๋๊ฒจ์ฃผ๋๋ก ์์
public String createQuestion(QuestionDto.RequestQuestionForm requestQuestionForm) {
questionService.createQuestion(requestQuestionForm.getSubject(), requestQuestionForm.getContent());
return "question_list";
}
}
โข Service ์์ ์ง๋ฌธ ์ ์ฅ
- Question ์ ์์ฑ์ ์์ฑ
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Entity // ์๋ Question ํด๋์ค๋ ์ํฐํฐ ํด๋์ค์ด๋ค.
// ์๋ ํด๋์ค์ 1:1๋ก ๋งค์นญ๋๋ ํ
์ด๋ธ์ด DB์ ์๋ค๋ฉด, ์๋์ผ๋ก ์์ฑ๋์ด์ผ ํ๋ค.
public class Question {
// (์๋ต)
public Question (String subject, String content) { // ์์ฑ์ ์์ฑ
this.subject = subject;
this.content = content;
this.createDate = LocalDateTime.now();
}
}
- Service ์์ฑ
@RequiredArgsConstructor
@Service
public class QuestionService {
public void createQuestion(String subject, String content) {
Question question = new Question(subject, content);
questionRepository.save(question);
}
}

3๏ธโฃ ์ง๋ฌธ ํผ์ ์ ํจ์ฑ ํ์ธ (์์ธ ์ฒ๋ฆฌ)
๋ฐ๋ก ์ ๋ฆฌ : https://like099.tistory.com/42
(Spring Boot) @Valid ์ ํจ์ฑ ์ฒ๋ฆฌ ํ์ฉ (feat. BindingResult)
๐ ํด๊ฒฐํ๊ณ ์ ํ๋ ์ํฉ ์ง๋ฌธ ํผ์ ์์ฑํ์ฌ POST request ๋ฅผ ๋ ๋ฆฌ๋ฉด Controller ์์ ์ ํจ์ฑ์ ํ์ธ ํ ๋ฌธ์ ๊ฐ ์์ผ๋ฉด Service ๋ก ๋๊ฒจ ์ ์ฅ, ๋ฌธ์ ๊ฐ ์์ผ๋ฉด ๋ฌธ์ ๋ฅผ ์ง๋ฌธํผ View ๋ก ๋๊ฒจ์ ์ฌ์ฉ์์๊ฒ
like099.tistory.com
'TIL ๐' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| TIL 10์ผ์ฐจ (2022.10.20) (0) | 2022.10.20 |
|---|---|
| TIL 9์ผ์ฐจ (2022.10.19) (0) | 2022.10.19 |
| TIL 7์ผ์ฐจ (2022.10.17) (0) | 2022.10.17 |
| TlL 6์ผ์ฐจ (2022.10.14) (0) | 2022.10.14 |
| TIL 5์ผ์ฐจ (2022.10.13) (0) | 2022.10.13 |