Bibi's DevLog ๐Ÿค“๐ŸŽ

[Spring] @RequestParam, @PathVariable ์ฐจ์ด ๋ณธ๋ฌธ

๐Ÿ–ฅ BE ๋ฐฑ์—”๋“œ/Spring ์Šคํ”„๋ง

[Spring] @RequestParam, @PathVariable ์ฐจ์ด

๋น„๋น„ bibi 2021. 3. 11. 00:05

[Spring] @RequestParam, @PathVariable ์ฐจ์ด

์ฐธ๊ณ  : ๋ธ”๋กœ๊ทธ.

์›Œ๋‚™ ์„ค๋ช…์ด ์ž˜ ๋˜์–ด ์žˆ์–ด ๋‚˜๋Š” ๊ฐ„๋‹จํžˆ ์ •๋ฆฌ๋งŒ ํ•˜๊ธฐ๋กœ ํ–ˆ๋‹ค. ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!

๋‘˜ ๋‹ค Spring์—์„œ URL์„ ํ†ตํ•ด ํด๋ผ์ด์–ธํŠธ๋กœ๋ถ€ํ„ฐ Controller์— ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ์ „๋‹ฌ๋ฐ›์„ ๋•Œ ์‚ฌ์šฉํ•˜๋Š” ์–ด๋…ธํ…Œ์ด์…˜์ด๋‹ค.

@RequestParam

http://127.0.0.1?index=1&page=2 ์™€ ๊ฐ™์€ ํ˜•์‹์˜ URL์—์„œ ํŒŒ๋ผ๋ฏธํ„ฐ ๊ฐ’์„ ๋ฐ›์•„์˜ฌ ๋•Œ ์ฃผ๋กœ ์‚ฌ์šฉ.

(์ด๋ฆ„&๊ฐ’ ์ „๋‹ฌ)

ํŒŒ๋ผ๋ฏธํ„ฐ ์ด๋ฆ„ = index, page, ...

ํŒŒ๋ผ๋ฏธํ„ฐ ๊ฐ’ = 1, 2 ...

@GetMapping("read")
public ModelAndView getFactoryRead(@RequestParam("index") int indexNum, SearchCriteria criteria) 
{
  //...    
}

@PathVariable

http://127.0.0.1/index/1์™€ ๊ฐ™์€ ํ˜•์‹์˜ URL์—์„œ (RestAPI) ๊ฐ’์„ ํ˜ธ์ถœํ•  ๋•Œ ์ฃผ๋กœ ์‚ฌ์šฉ.

@PostMapping("delete/{idx}")
@ResponseBody
public JsonResultVo postDeleteFactory(@PathVariable("index") int indexNum) {
    return factoryService.deleteFacotryData(indexNum);
}

์•„๋ž˜์™€ ๊ฐ™์ด ๋ณตํ•ฉ์ ์œผ๋กœ ์‚ฌ์šฉํ•  ์ˆ˜๋„ ์žˆ๋‹ค.

@GetMapping("/user/{userIdx}/invoices")
public List<Invoice> listUsersInvoices(
    @PathVariable("userIdx") int user,
    @RequestParam(value = "date", required = false) Date dateOrNull
){
    // codes..
}