@Controller
- ํด๋น ์ ๋ํ ์ด์ ์ ์๋ต์ ๋ํด์ ๋ฌธ์์ด ๊ฒฝ๋ก๋ฅผ ๋ฆฌํด์ ํ๋ฉด ํด๋น ๊ฒฝ๋ก์ ์ ๋ฏธ์ด(suffix)๊ฐ ์ค์ ์ ๋ฐ๋ผ ์๋์ผ๋ก ๋ถ๊ฒ ๋จ.
- ์์) html, jsp ๋ฑ
- ๋ฆฌํด์ด ๋๋ฉด DispatcherServlet์ ํตํด ๋ทฐ ๋ฆฌ์กธ๋ฒ์ ๋ฆฌํด์ด ๋์ด ํด๋น html ๋ทฐ๋ฅผ ๋ฆฌํด์ ํด์ค๋ค.
@RestController
- Controller์ ResponseBody ์ ๋ํ ์ด์ ์ด ํฉ์ฑ ๋์ด์๋ ์ ๋ํ ์ด์ ์.
- ResponseBody: ์ปจํธ๋กค๋ฌ์ ๋ฉ์๋ ๋ฐํ ๊ฐ์ HTTP ์๋ต์ Body์ ์ง์ ์ฐ๋๋ก ์ง์ํ๋ ๋ฉํ๋ฐ์ดํฐ์
@ResponseBody
- ์ปจํธ๋กค๋ฌ์ ๋ฉ์๋ ๋ฐํ ๊ฐ์ HTTP ์๋ต์ Body์ ์ง์ ์ฐ๋๋ก ์ง์ํ๋ ๋ฉํ๋ฐ์ดํฐ์
- ๋ฉ์๋์์ ๋ฆฌํด์ ํ๊ฒ ๋๋ฉด ๋ด๋ถ์ ์ผ๋ก HttpMessageConverter์๊ฒ ๋ฐ์ดํฐ๋ฅผ ๋๊ฒจ ์๋ต ๋ฐ์ดํฐ๋ฅผ ๋ณํํ๊ฒ ๋จ.
@RequestBody
- ์์ฒญ์ ๋์ด์ค๋ ๋ฐ์ดํฐ๋ฅผ ๊ฐ์ฒด๋ก ๋ฐ์ธ๋ฉํ๊ธฐ ์ํด ์ ๊ณต๋๋ ์ ๋ํ ์ด์
- ์ฝ๊ฒ ๋งํด, ๋ฐ์ดํฐ๊ฐ json ํํ๋ก ๋์ด์ค๋ฉด ์ ๋ํ ์ด์ ์ ํตํด ๊ฐ์ฒด์ ํ๋๋ก ๋ฐ์ธ๋ฉ๋์ด ๊ฐ์ด ๋ค์ด๊ฐ๊ฒ ๋๋ ์๋ฆฌ์.
- ๋ด๋ถ์ ์ผ๋ก ํค๋์ Content-Type์ ํ์ธํ ๋ค json์ด๋ฉด, MappingJackson2HttpMessageConverter ํด๋์ค๋ฅผ ํ์ฉํจ.
SpringBoot ๊ธฐ์ค ์์ฃผ ์ฐ์ด๋ Converter ์ข ๋ฅ
StringHttpMessageConverter | text/plain ๋ฌธ์์ด ๋ณํ |
MappingJackson2HttpMessageConverter | application/json ๋ณํ (Jackson ์ฌ์ฉ) |
ByteArrayHttpMessageConverter | ๋ฐ์ด๋๋ฆฌ ์ฒ๋ฆฌ (ํ์ผ ๋ค์ด๋ก๋ ๋ฑ) |
FormHttpMessageConverter | application/x-www-form-urlencoded ํผ ๋ฐ์ดํฐ ์ฒ๋ฆฌ |
Jaxb2RootElementHttpMessageConverter | application/xml ๋ฑ XML ์ฒ๋ฆฌ (JAXB ๊ธฐ๋ฐ) |
- ์ฐธ๊ณ ๋ก HttpMessageConverter ์ธํฐํ์ด์ค ๊ตฌํํด์ Custom Converter ๋ ๋ง๋ค ์ ์์.
HttpMessageConverter
- Spring MVC์์ HTTP ์์ฒญ๊ณผ ์๋ต์ ๋ณธ๋ฌธ์ Java ๊ฐ์ฒด์์ ๋ค์ํ ํฌ๋งท์ผ๋ก ์ง๋ ฌํ ๋ฐ ์ญ์ง๋ ฌํ ํด์ฃผ๋ ์ธํฐํ์ด์ค์ด๋ค.
- ์ฝ๊ฒ๋งํด, ์ ๋ต ์ธํฐํ์ด์ค๋ก ๊ฐ์ฒด๋ฅผ JSON, XML, text ๋ฑ์ผ๋ก ๋ณํ ํด์ฃผ๋ ๊ฒ์ด ์ง๋ ฌํ์.
- ๋ฐ๋๋ก ์ญ์ง๋ ฌํ๋ ํด๋ผ์ด์ธํธ๋ก ๋ถํฐ ๋์ด์ค๋ ๋ฐ์ดํฐ์ ํ์์ ๊ฐ์ฒด๋ก ๋ฐ์ธ๋ฉ์ ํด์ฃผ๋๊ฒ์.
- @ResponseBody, @ReuqestBody ์ ๋ํ ์ด์ ์ ๋ํดํธ๋ก MappingJackson2HttpMessageConverter ํด๋์ค๋ฅผ ์ด์ฉํจ.
- ์ฆ, ์์ฒญ๊ณผ ์๋ต์ JSON ํํ๋ก ์ฃผ๊ณ ๋ฐ๋๊ฒ์ด ๋ํดํธ๋ผ๋ ์๋ฏธ์.
๋ฆฌํด๊ฐ์ด ResponseEntity ์ธ ๊ฒฝ์ฐ
- HttpEntityMethodProcessor ํด๋์ค๊ฐ ์ ํ์ด ๋๊ณ ResponseEntity ๋ด๋ถ์ body ๋ฑ ๋ฐ์ดํฐ๋ฅผ HttpServletResponse ๋ฃ์.
- ํด๋น ํด๋์ค๋ HandlerMethodReturnValueHandler์ ๊ตฌํ์ฒด์ด๋ค.
- HttpMessageConverter ๋ด๋ถ์์ HttpServletResponse ํด๋์ค ๋ด๋ถ๋ฅผ ํ์ ํ ๋ค
- body, status, header ๋ถ๋ถ์ ๋ค์ด๊ฐ ์๋๊ฐ์ ๋ฝ์์ JSON ๋ฐ์ดํฐ๋ก ๋ง๋ค์ด์ ํด๋น ๋ฐ์ดํฐ๋ฅผ
'๐ณSpring > ๐ฑSpring Framework' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Spring Framework] DispatcherServle (0) | 2025.05.12 |
---|---|
[Spring Framework] IoC ์ปจํ ์ด๋ ๋์ ์๋ฆฌ (0) | 2024.11.14 |
[Spring Framework] IoC ์ปจํ ์ด๋ & Bean ๊ฐ๋ ์ดํด ํ๊ธฐ (1) | 2024.10.21 |
[Spring Framework] IoC & DI ๊ฐ๋ ์ดํด ํ๊ธฐ (0) | 2024.10.20 |
[Spring Framework] Spring & Spring Framework ์ฐจ์ด (0) | 2024.10.19 |