Spring

[Spring] @RequestBody / @ResponseBody ์ฐจ์ด

natrue 2021. 5. 28. 15:39
728x90

HTTP  : ๋ฐ์ดํ„ฐ๋ฅผ ์ฃผ๊ณ ๋ฐ›๊ธฐ ์œ„ํ•œ ํ”„๋กœํ† ์ฝœ 

HTTP๋Š” ํด๋ผ์ด์–ธํŠธ์™€ ์„œ๋ฒ„ ์‚ฌ์ด์— ์ด๋ฃจ์–ด์ง€๋Š” ์š”์ฒญ/์‘๋‹ต(request/response) ํ”„๋กœํ† ์ฝœ์ด๋‹ค. 

HTTP Body ์•ˆ์—” XML ๋˜๋Š” JSON์ด ๋“ค์–ด๊ฐ„๋‹ค. 

@RequestBody : HTTP Body์•ˆ์— JSON์„ VO์— ๋งตํ•‘ํ•˜๋Š” ์Šคํ”„๋ง ์–ด๋…ธํ…Œ์ด์…˜. 

@RequestBody ์–ด๋…ธํ…Œ์ด์…˜์„ ์ด์šฉํ•˜๋ฉด HTTP ์š”์ฒญ Body๋ฅผ ์ž๋ฐ” ๊ฐ์ฒด๋กœ ์ „๋‹ฌ๋ฐ›์„ ์ˆ˜ ์žˆ๋‹ค.

Ajax์—์„œ ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ์ปจํŠธ๋กค๋Ÿฌ์— ๋ณด๋‚ด๋ฉด ์ปจํŠธ๋กค๋Ÿฌ์—์„  @RequestBody๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ๋ฐ›๋Š”๋‹ค. 

@RequestMapping(value = "/requestBodyTest.do") 
public String requestBodyTest(@RequestBody UserVO vo) throws Exception {
	return "test/login"; 
}

@ResponseBody : VO ๊ฐ์ฒด๋ฅผ JSON์œผ๋กœ ๋ฐ”๊ฟ” HTTP Body์•ˆ์— ๋‹ด๋Š” ์Šคํ”„๋ง ์–ด๋…ธํ…Œ์ด์…˜. 

์š”์ฒญํ•œ ํ˜•ํƒœ์— ๋งž์ถฐ์„œ ๋ฉ”์‹œ์ง€ ๋ณ€ํ™˜๊ธฐ๋ฅผ ํ†ตํ•ด ๊ฒฐ๊ณผ ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

 @ResponseBody์„ ์ด์šฉํ•˜๋ฉด ์ž๋ฐ” ๊ฐ์ฒด๋ฅผ HTTP ์‘๋‹ต body๋กœ ์ „์†กํ•  ์ˆ˜ ์žˆ๋‹ค.

@ResponseBody 
@RequestMapping(value = "/responseBodyTest.do") 
public UserVO responseBodyTest() throws Exception { 
  UserVO vo = new UserVO(); 
  vo.setId("ํ…Œ์ŠคํŠธ"); 
  
  return vo; 
}

 

 ์š”์ฒญ : requestBody

 ์‘๋‹ต : responseBody