[Spring] @PathVariable ๊ทธ๋ฆฌ๊ณ  @RequestParam

2022. 3. 22. 23:05ใ†Back-End ์ž‘์—…์‹ค/Spring Framework

728x90
๋ฐ˜์‘ํ˜•

 

๐Ÿš€ ๊ฐœ์š”

Spring์œผ๋กœ Web Service๋ฅผ ๋งŒ๋“ค๊ธฐ ์œ„ํ•ด Controller๋ฅผ ๋งŒ๋“ค๊ฒŒ ๋˜๋ฉด Client์—์„œ URI์— Parameter๋กœ ์š”์ฒญ์„ ํ•˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ์žˆ๋Š” ๊ฒƒ์ด์—์š”.

์ด ๋•Œ ์•„๋ž˜ ๋‘ ๊ฐ€์ง€๋ฅผ ์ด์šฉํ•ด์„œ ์š”์ฒญ์„ ํ•˜๊ฒŒ ๋˜๋Š”๊ฒŒ ๋Œ€ํ‘œ์ ์ด๋ž๋‹ˆ๋‹ค.

์ฒซ์งธ : http//localhost?index=1&page=2
๋‘˜์งธ : http://localhost/index/1

 

์ฒซ๋ฒˆ์งธ์˜ ๊ฒฝ์šฐ Parameter์˜ ๊ฐ’๊ณผ Key(name - ์ด๋ฆ„)์„ ํ•จ๊ป˜ ์ „๋‹ฌํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ Query String์ด๋ผ๊ณ ๋„ ํ•˜๋ฉฐ, ๊ฒŒ์‹œํŒ ๋“ฑ์—์„œ Page ๊ฒ€์ƒ‰ ๋ฐ ๊ฒ€์ƒ‰ ์ •๋ณด๋ฅผ ์ „๋‹ฌํ•˜๋Š” ๊ฒฝ์šฐ ๋งŽ์ด ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด์—์š”.

๋‘๋ฒˆ์งธ ๊ฒฝ์šฐ๋Š” REST API์—์„œ ๊ฐ’์„ ํ˜ธ์ถœํ•  ๋•Œ, ์ด์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•์ด๋ž๋‹ˆ๋‹ค.

 

    ๐Ÿ”ฝ  @RequestParam

๊ฐœ์š”์—์„œ ์ฒซ๋ฒˆ์งธ์˜ ๊ฒฝ์šฐ @RequestParam์„ ์ด์šฉํ•˜๊ฒŒ ๋˜๋Š” ๊ฒƒ์ด์—์š”.

์•„๋ž˜ ์˜ˆ์ œ์ฝ”๋“œ์™€ ๊ฐ™์ด Controller ์—์„œ ์ด์šฉํ•˜๊ฒŒ ๋˜๋Š” ๊ฒƒ์ด์—์š”.

์˜ˆ์ œ ์ฝ”๋“œ

@GetMapping("/test")
public ModelAndView getFactoryRead(@RequestParam("no") int factroyId, SearchCriteria criteria) {
  //...    
} // getFactoryRead(@RequestParam("no") ๋

์œ„ ๊ทธ๋ฆผ์ฒ˜๋Ÿผ ์ •์˜๋ฅผ ํ•œ ๋’ค Front End์—์„œ ์š”์ฒญ์„ ๋ณด๋‚ด๊ธฐ ์œ„ํ•ด์„œ URI์— `/test?no=1`๊ณผ ๊ฐ™์ด URI๊ฐ€ ์ „๋‹ฌ ๋  ๋•Œ, no Parameter๋ฅผ ๋ฐ›์•„์˜ค๊ฒŒ ๋˜๋Š” ๊ฒƒ์ด์—์š”.

์ด ์นœ๊ตฌ์— ์†Œ๊ด„ํ˜ธ ์•ˆ์— ์ „๋‹ฌํ•˜๊ณ ์ž ํ•˜๋Š” ์ธ์ž์˜ ์ด๋ฆ„ (์‹ค์ œ ๊ฐ’)์„ ์ ์–ด์ฃผ๋ฉด ๋˜๋Š” ๊ฒƒ์ด์—์š”.

@RequestParam์˜ ๊ฒฝ์šฐ URI ๋’ค์— ๋ถ™๋Š” Parameter ๊ฐ’์„ ๊ฐ€์ ธ์˜ฌ ๋•Œ, ์ด์šฉํ•œ๋‹ต๋‹ˆ๋‹ค.

 

 

 

 

    ๐Ÿ”ฝ  @PathVariable

๋‘๋ฒˆ์งธ์˜ ๊ฒฝ์šฐ @PathVariable์„ ์ด์šฉํ•˜๊ฒŒ ๋˜๋Š” ๊ฒƒ์ด์—์š”.

 

์˜ˆ์ œ ์ฝ”๋“œ

@PostMapping("/test/{idx}")
@ResponseBody
public JsonResultVo postDeleteFactory(@PathVariable("idx") int idx) {
	return factoryService.deleteFacotryData(factoryIdx);
} // postDeleteFactory(int factoryIdx) ๋
๋ฐ˜์‘ํ˜•

 

์œ„์— ์˜ˆ์ œ ์ฝ”๋“œ์ฒ˜๋Ÿผ `PathVariable`์˜ ๊ฒฝ์šฐ URI์—์„œ ๊ฐ ๊ตฌ๋ถ„์ž์— ๋“ค์–ด์˜ค๋Š” ๊ฐ’์„ ์ฒ˜๋ฆฌํ•ด์•ผ ๋  ๋•Œ ์ด์šฉํ•˜๋Š” ๊ฒƒ์ด์—์š”.

 

๋งŒ์•ฝ FrontEnd๊ฐ€ ์š”์ฒญ์„ ๋ณด๋‚ผ ๋•Œ `http://localhost:8080/test/1`๊ณผ ๊ฐ™์ด ์š”์ฒญ์„ ๋ณด๋‚ด๊ฒŒ ๋œ๋‹ค๋ฉด {idx}์—๋Š” 1์ด ๋“ค์–ด๊ฐ€๊ฒŒ ๋˜๊ณ , Method ๋งค๊ฐœ ๋ณ€์ˆ˜๋กœ 3์ด๋ผ๋Š” ๊ฐ’์ด ๋“ค์–ด์˜ค๊ฒŒ ๋˜๋Š” ๊ฒƒ์ด์—์š”.

๋งŒ์•ฝ ์œ„์™€ ๊ฐ™์ด '1'์„ ๋„ฃ์–ด์ฃผ์ง€ ์•Š๊ณ , `http://localhost:8080/test/`์ด๋ ‡๊ฒŒ๋งŒ ์š”์ฒญ์„ ๋ณด๋‚ด๊ฒŒ ๋˜๋ฉด ์•„๋ž˜์™€ ๊ฐ™์€ Error๊ฐ€ ๋ฐœ์ƒํ•˜๊ฒŒ ๋˜๋Š” ๊ฒƒ์ด์—์š”.

 

๋งŒ์•ฝ์— `http://localhost:8080/test/` ์ด๋ ‡๊ฒŒ URI๋ฅผ ๋ณด๋‚ด๋Š” ๊ฒƒ๋„ ํ—ˆ์šฉํ•˜๊ณ ์ž ํ•œ๋‹ค๋ฉด ์•„๋ž˜์™€ ๊ฐ™์ด Controller๋ฅผ ์ˆ˜์ • ํ•ด ์ฃผ๋ฉด ๋˜๋Š” ๊ฒƒ์ด์—์š”.

 

@PostMapping("/test/{idx}, "/test")
@ResponseBody
public JsonResultVo postDeleteFactory(@PathVariable("idx") int idx) {
	return factoryService.deleteFacotryData(factoryIdx);
} // postDeleteFactory(int factoryIdx) ๋

 

 

 

 

 

 

 

 

 

728x90
๋ฐ˜์‘ํ˜•