[์คํ๋ง MVC] - 18. Redirect / Post -> Redirect -> Get

POST ๋ฑ๋ก ํ ์๋ก ๊ณ ์นจ

์น ๋ธ๋ผ์ฐ์ ์ ์๋ก ๊ณ ์นจ์ ๋ง์ง๋ง์ ์๋ฒ์ ์ ์กํ ๋ฐ์ดํฐ๋ฅผ ๋ค์ ์ ์กํ๋ค.
์ํ ๋ฑ๋ก ํผ์์ ๋ฐ์ดํฐ๋ฅผ ์
๋ ฅํ๊ณ ์ ์ฅ์ ์ ํํ๋ฉด POST /add + ์ํ ๋ฐ์ดํฐ๋ฅผ ์๋ฒ๋ก ์ ์กํ๋ค.
์ด ์ํ์์ ์๋ก ๊ณ ์นจ์ ๋ ์ ํํ๋ฉด ๋ง์ง๋ง์ ์ ์กํ POST /add + ์ํ ๋ฐ์ดํฐ๋ฅผ ์๋ฒ๋ก ๋ค์ ์ ์กํ๊ฒ ๋๋ค.
๊ทธ๋์ ๋ด์ฉ์ ๊ฐ๊ณ , ID๋ง ๋ค๋ฅธ ์ํ ๋ฐ์ดํฐ๊ฐ ๊ณ์ ์์ด๊ฒ ๋๋ค.
์ด ๋ฌธ์ ๋ฅผ ์ด๋ป๊ฒ ํด๊ฒฐํ ์ ์์๊น?
POST, Redirect GET

์น ๋ธ๋ผ์ฐ์ ์ ์๋ก ๊ณ ์นจ์ ๋ง์ง๋ง์ ์๋ฒ์ ์ ์กํ ๋ฐ์ดํฐ๋ฅผ ๋ค์ ์ ์กํ๋ค.
์๋ก ๊ณ ์นจ ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๋ ค๋ฉด ์ํ ์ ์ฅ ํ์ ๋ทฐ ํ
ํ๋ฆฟ์ผ๋ก ์ด๋ํ๋ ๊ฒ์ด ์๋๋ผ,
์ํ ์์ธ ํ๋ฉด์ผ๋ก ๋ฆฌ๋ค์ด๋ ํธ๋ฅผ ํธ์ถํด์ฃผ๋ฉด ๋๋ค.
์น ๋ธ๋ผ์ฐ์ ๋ ๋ฆฌ๋ค์ด๋ ํธ์ ์ํฅ์ผ๋ก ์ํ ์ ์ฅ ํ์ ์ค์ ์ํ ์์ธ ํ๋ฉด์ผ๋ก ๋ค์ ์ด๋ํ๋ค.
๋ฐ๋ผ์ ๋ง์ง๋ง์ ํธ์ถํ ๋ด์ฉ์ด ์ํ ์์ธ ํ๋ฉด์ธ GET /items/{id} ๊ฐ ๋๋ ๊ฒ์ด๋ค.
@PostMapping("/add")
public String addItem(@ModelAttribute("item") Item item) {
itemRepository.save(item);
// model.addAttribute("item",item);
return "redirect:/basic/items/" + item.getId();
}

RedirectAttributes
RedirectAttributes ๋ฅผ ์ฌ์ฉํ๋ฉด URL ์ธ์ฝ๋ฉ๋ ํด์ฃผ๊ณ , pathVarible , ์ฟผ๋ฆฌ ํ๋ผ๋ฏธํฐ๊น์ง ์ฒ๋ฆฌํด์ค๋ค.
@PostMapping("/add")
public String addItem(@ModelAttribute("item") Item item,
RedirectAttributes redirectAttributes) {
Item savedItem = itemRepository.save(item);
redirectAttributes.addAttribute("itemId",savedItem.getId());
redirectAttributes.addAttribute("status", true);
return "redirect:/basic/items/{itemId}";
}
pathVariable ๋ฐ์ธ๋ฉ: {itemId}
๋๋จธ์ง๋ ์ฟผ๋ฆฌ ํ๋ผ๋ฏธํฐ๋ก ์ฒ๋ฆฌ: ?status=true
<h2 th:if="${param.status}" th:text="'์ ์ฅ ์๋ฃ!'"></h2>
th:if : ํด๋น ์กฐ๊ฑด์ด ์ฐธ์ด๋ฉด ์คํ
${param.status} : ํ์๋ฆฌํ์์ ์ฟผ๋ฆฌ ํ๋ผ๋ฏธํฐ๋ฅผ ํธ๋ฆฌํ๊ฒ ์กฐํํ๋ ๊ธฐ๋ฅ

https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-mvc-1/dashboard
์คํ๋ง MVC 1ํธ - ๋ฐฑ์๋ ์น ๊ฐ๋ฐ ํต์ฌ ๊ธฐ์ - ์ธํ๋ฐ | ๊ฐ์
์น ์ ํ๋ฆฌ์ผ์ด์ ์ ๊ฐ๋ฐํ ๋ ํ์ํ ๋ชจ๋ ์น ๊ธฐ์ ์ ๊ธฐ์ด๋ถํฐ ์ดํดํ๊ณ , ์์ฑํ ์ ์์ต๋๋ค. ์คํ๋ง MVC์ ํต์ฌ ์๋ฆฌ์ ๊ตฌ์กฐ๋ฅผ ์ดํดํ๊ณ , ๋ ๊น์ด์๋ ๋ฐฑ์๋ ๊ฐ๋ฐ์๋ก ์ฑ์ฅํ ์ ์์ต๋๋ค., -
www.inflearn.com