DevKim

Controller์˜ ์ „๋‹ฌ์ธ์ž ์ฐจ์ด์  ๋ณธ๋ฌธ

Spring Boot

Controller์˜ ์ „๋‹ฌ์ธ์ž ์ฐจ์ด์ 

on_doing 2021. 7. 5. 11:43
728x90

๐Ÿ”— @RequestParam

@RequestParam("id") Long id
  • http://์ฃผ์†Œ๊ฐ’?index=1&page=2
  • ํ•ด๋‹น Request์— ๋Œ€ํ•œ ํŒŒ๋ผ๋ฏธํ„ฐ๋“ค์„ ์ž๋™์œผ๋กœ bindingํ•œ๋‹ค.
  • ํ•œ๊ฐœ์˜ HTTP ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ์–ป๊ธฐ ์œ„ํ•ด์„œ ์ฃผ๋กœ ์‚ฌ์šฉ๋จ

** ์ฃผ์˜ ํ•  ์  **

  • ๋‹จ์ผ ๊ฐ’๋งŒ binding ๊ฐ€๋Šฅํ•˜๋ฉฐ, ๋งŒ์•ฝ List ํ˜•ํƒœ๋กœ ๋ณต์ˆ˜์˜ ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ Requestํ•˜๋ฉด ์ฒซ๋ฒˆ์งธ Data๊ฐ’๋งŒ binding๋œ๋‹ค.
@ReqeustParam HashMap<String,Object> params //{id=gil, name=gillog}
  • MultiValueMap์„ ์ด์šฉํ•˜์—ฌ List ํ˜•ํƒœ์˜ ๊ฐ’๋“ค์„ value๋กœ binding ํ•  ์ˆ˜ ์žˆ์Œ
@ReqeustParam MultiValueMap<String, String> multiParams 

//{id=[gil], name=[gillog, loadbear]} 
//ํ•˜๋‚˜์˜ ํŒŒ๋ผ๋ฏธํ„ฐ์— ์—ฌ๋Ÿฌ Data๋ฅผ ์ „์†ก๋ฐ›์•„์•ผํ•  ๋•Œ ์ฃผ๋กœ ์‚ฌ์šฉ

๐Ÿ”— @PathVariable

@PathVariable("id") Long id

๐Ÿ”— @RequestBody

  • ํด๋ผ์ด์–ธํŠธ๊ฐ€ ์ „์†กํ•˜๋Š” JSON ํ˜•ํƒœ์˜ HTTP Body ๋‚ด์šฉ์„ Java ๊ฐ์ฒด๋กœ ๋ณ€ํ™˜ํ•ด์„œ ๋ฐ›์•„์˜ค๋Š” ์—ญํ• 

๐Ÿ”— Model ๊ฐ์ฒด ์‚ฌ์šฉ

  • public void ๋ฉ”์†Œ๋“œ๋ช…(Model model)
  • model.addAttrbute("key๊ฐ’","value๊ฐ’") view์— ์ „๋‹ฌ ํ•  ๋ฐ์ดํ„ฐ๋ฅผ ์Œ์œผ๋กœ ์ „๋‹ฌ

๐Ÿ”— @ModelAttribute (Setter ํ•„์ˆ˜)

@ModelAttribute Model model

  • multipart/form-data ํ˜•ํƒœ์˜ HTTP Body ๋‚ด์šฉ๊ณผ ํŒŒ๋ผ๋ฏธํ„ฐ๋“ค์„ setter์„ ํ†ตํ•ด 1๋Œ€1๋กœ Java ๊ฐ์ฒด์— ๋ฐ”์ธ๋”ฉํ•ด์ฃผ๋Š” ์—ญํ• 
  • ๋ณ€ํ™˜์ด ์•„๋‹Œ ๋ฐ”์ธ๋”ฉ์„ ์‹œํ‚ค๋ฏ€๋กœ, ๋ณ€์ˆ˜๋“ค์˜ setter ํ•จ์ˆ˜๊ฐ€ ์—†์œผ๋ฉด ๋ณ€์ˆ˜๋“ค์ด ์ €์žฅ๋˜์ง€ ์•Š์Œ
  • ์ „๋‹ฌ๊ฐ’์„ ๊ฐ์ฒด ํ˜•ํƒœ๋กœ ๋งคํ•‘ํ•ด์ฃผ๋Š” ์–ด๋…ธํ…Œ์ด์…˜
  • ๊ฒ€์ƒ‰ ์กฐ๊ฑด์ด ์ค„์–ด๋“ค๊ฑฐ๋‚˜ ๋Š˜์–ด๋‚˜๋Š” ๋ณ€๊ฒฝ์ด ๋ฐœ์ƒํ–ˆ์„ ๋•Œ, 1:1๋งคํ•‘์„ ํ–ˆ์„ ์‹œ์— ์ˆ˜์ •ํ•ด์ค˜์•ผํ•˜๋Š” ๋ถ€๋ถ„๋“ค์„ ์ˆ˜์ •ํ•˜์ง€ ์•Š์•„๋„๋œ๋‹ค๋Š” ์žฅ์ ์ด ์žˆ์Œ
  • ํŠน์ • ํŒŒ๋ผ๋ฏธํ„ฐ๋งŒ binding ํ•  ์ˆ˜๋„ ์žˆ์Œ
@ModelAttribute('writer') String writer 

//{ writer: 'gillog', contents : 'ModelAttributeStudy' }
728x90
Comments