8๋ ์ ์คํ๋ง์ ์ฒ์ ์ ํ ์ดํ Nest.js๋ฅผ ์ค๋ฌด์์ ์ฐ๋ฉฐ ์คํ๋ง์ ๋ํ ํฅ๋ฏธ๊ฐ ์ ์ ๋ค์ ์๊ฒจ๋ฌ๋ค.
์๊ทผ๋ ์ด๊ฒ์ ๊ฒ ์ฐพ์๋ณด๋ ์ฌ๊ฑธ,,์คํ๋ง๋ ์๋๊ณ ์คํ๋ง ๋ถํธ๋ฅผ ๋๋ค์๊ฐ ์ฌ์ฉํ๋ค
์คํ๋ง๋ถํธ๋ก ํ๋ก์ ํธ๋ฅผ ๋ง๋ค์ด๋ณด๊ณ , ํ๋ํ๋ ๋ค์ ๊ณต๋ถํด๋ณด๋๋ฐ ๋ถ๋ช ํ ๋ด ๊ธฐ์ต์ @Controller ์ ๋ ธํ ์ด์ ์ ์ผ๋๊ฑฐ ๊ฐ์๋ฐ ์ด๋์๊ฐ @RestController๋ฅผ ์ฐ๊ณ ์์ด ์ฐจ์ด์ ์ด ๊ถ๊ธํด์ก๋ค
๊ฐ์ฅ ํฐ ์ฐจ์ด์ , ๋ฐ์ดํฐ๋ฅผ ์ด๋ป๊ฒ ๋ฐํํ๋๋?

@Controller
- Spring mvc ์ปจํธ๋กค๋ฌ๋ ์ฃผ๋ก View ๋ฐํ ์ํด ์ฌ์ฉ๋์๊ณ , ViewResolver ํตํด ํ๋ฉด์ ์ฐพ๋๋ค
-> ๋ฉ๋ดํ์ ๋ณด๊ณ ์ฃผ๋ฐฉ์ผ๋ก ์๋ด
- ๋ฐ์ดํฐ๋ฅผ ๋ฐํํด์ผํ๋ ๊ฒฝ์ฐ๊ฐ ์๋๋ฐ ๊ทธ๋ @ResponseBody๋ฅผ ์ฌ์ฉํ์ฌ JSON ํํ๋ก ๋ฐ์ดํฐ ๋ฐํํ์๋ค
- @ResponseBody๋ฅผ ์ฌ์ฉํ์ง ์์ผ๋ฉด ํด๋น๋๋ ๋ฐํ๊ฐ์ HTML์ ์ฐพ๋๋ค
@Controller + @ResponseBody ์ผ๋ ๋์ ์์
- ์ปจํธ๋กค๋ฌ๋ฅผ ํตํด ๊ฐ์ฒด๋ฅผ ๋ฐํํ ๋์๋ ResponseEntity๋ก ๊ฐ์ธ์ ๋ฐํ์ ํ๋ค.
- ์ด๋ View Resolver ๋์ HttpMessageConverter๊ฐ ๋์ํ๋ค (6๋ฒ๋์)
@RestController
- @Controller์ ๋ค๋ฅด๊ฒ ๋ฐ์ดํฐ ๋ฐํ์ @ResponseBody ์ ์ธ ์์ด ๊ฐ๋ฅํ๊ฒ ํด์ค๋ค
- JSON, XML ํํ๋ก ๋ฐํ ๊ฐ๋ฅํ๋ค
- HTTP Response Body์ ๋ฐ์ดํฐ๋ฅผ ์ง์ ๊ธฐ๋กํ๋ค
-> ์ฃผ๋ฌธํ ์์์ ๊ทธ ์๋ฆฌ์์ ๋ฐ๋ก ์ค๋ค
- @Controller + @ResponseBody ์ ๋์๊ณผ ์ผ์นํ๊ฒ ์๋ํ๋ค
์ฝ๋๋ก ๋น๊ตํ๊ธฐ
1. @Controller ๋ฐฉ์
@Controller
public class UserController {
@GetMapping("/user/controller")
@ResponseBody // ์ด๊ฒ ์์ผ๋ฉด ViewResolver๊ฐ "user"๋ผ๋ ๋ทฐ๋ฅผ ์ฐพ์ผ๋ ค ํจ!
public User getUser() {
return new User("Gemini", 2026);
}
}
2. @RestController ๋ฐฉ์
@RestController // ํด๋์ค ์ ์ฒด์ @ResponseBody๊ฐ ์ ์ฉ๋จ
public class UserRestController {
@GetMapping("/user/rest-controller")
public User getUser() {
return new User("Gemini", 2026);
}
}