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

Path Variable๊ณผ Query Parameter (์Šคํ”„๋ง์˜ @RequestParam๊ณผ @PathVariable) ๋ณธ๋ฌธ

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

Path Variable๊ณผ Query Parameter (์Šคํ”„๋ง์˜ @RequestParam๊ณผ @PathVariable)

๋น„๋น„ bibi 2021. 4. 30. 19:58

๊ฐ„๋‹จํ•˜๊ฒŒ ์š”์•ฝ ์ •๋ฆฌ๋งŒ ํ–ˆ๋‹ค.

์ถœ์ฒ˜

https://ryan-han.com/post/translated/pathvariable_queryparam/

https://elfinlas.github.io/2018/02/18/spring-parameter/

https://willbesoon.tistory.com/102

์‚ฌ์šฉ๋ฐฐ๊ฒฝ

  • http์—์„œ๋Š” ์š”์ฒญ ๊ฐ„ ๋ฐ์ดํ„ฐ๋ฅผ ๋ณด์žฅํ•ด ์ฃผ์ง€ ์•Š๋Š”๋‹ค.
  • ์—ฐ๊ฒฐ ํ•ด ๋†“๊ณ  ๋ฐ์ดํ„ฐ๋ฅผ ์ฃผ๊ณ ๋ฐ›๋Š” ํ˜•์‹์ด ์•„๋‹ˆ๋ผ, ํ•„์š”ํ•  ๋•Œ๋งˆ๋‹ค ์—ฐ๊ฒฐํ•œ๋‹ค.

๊ณตํ†ต์ 

  • ๋ฐ์ดํ„ฐ ์ „๋‹ฌ์„ ์œ„ํ•ด ์‚ฌ์šฉ๋œ๋‹ค.
  • URL์„ ํ†ตํ•ด ๊ฐ’์„ ์ „๋‹ฌํ•œ๋‹ค.

Query Parameter ์ฟผ๋ฆฌ ๋งค๊ฐœ๋ณ€์ˆ˜ (์Šคํ”„๋ง์˜ @RequestParam)

/users?id=123

  • ํŒŒ๋ผ๋ฏธํ„ฐ์˜ ์ด๋ฆ„๊ณผ ๊ฐ’์„ ํ•จ๊ป˜ ์ „๋‹ฌํ•˜๋Š” ๋ฐฉ์‹์ด๋‹ค

Best Practice : ์ •๋ ฌ / ํ•„ํ„ฐ๋ง์„ ํ•  ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค.

  • @RequestParam

    • 4๊ฐ€์ง€ ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ๊ฐ€์งˆ ์ˆ˜ ์žˆ๋‹ค

    • @RequestParam("id") : URL์˜ ํŒŒ๋ผ๋ฏธํ„ฐ ์ค‘ id๋ผ๋Š” ์ด๋ฆ„์˜ ๊ฐ’์„ ๊ฐ€์ ธ์˜จ๋‹ค

    • @GetMapping("read")
      public void getId(@RequestParam("no") int id) 
      {
        //...    
      }

Path Variable ๊ฒฝ๋กœ ๋ณ€์ˆ˜ (์Šคํ”„๋ง์˜ @PathVariable)

/users/123

  • ์ด๋ฆ„์ฒ˜๋Ÿผ ๊ฒฝ๋กœ๋ฅผ ๋ณ€์ˆ˜๋กœ์„œ ์‚ฌ์šฉํ•œ๋‹ค.

  • ์›ํ•˜๋Š” ๊ธฐ๋Šฅ์— ๋งž๊ฒŒ HTTP๋ฉ”์†Œ๋“œ๋ฅผ ๋ณ€๊ฒฝํ•œ๋‹ค.

  • REST API์—์„œ ๊ฐ’์„ ํ˜ธ์ถœํ•  ๋•Œ ์ฃผ๋กœ ์‚ฌ์šฉํ•œ๋‹ค.

Best Practice : ์–ด๋–ค ๋ฆฌ์†Œ์Šค๋ฅผ ์‹๋ณ„ํ•  ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค.

  • @PathVariable()

    • URL์—์„œ ๊ฐ ๊ตฌ๋ถ„์ž์— ๋“ค์–ด์˜ค๋Š” ๊ฐ’์„ ์ฒ˜๋ฆฌํ•œ๋‹ค

    • @PostMapping("delete/{id}")
      @ResponseBody
      public int getId(@PathVariable("id") int id) {
          return id;
      }

@RequestParam๊ณผ @PathVariable ํ•จ๊ป˜ ์‚ฌ์šฉํ•˜๊ธฐ

๋‘˜ ๋‹ค ํ•„์š”ํ•˜๋ฉด ๋‘˜ ๋‹ค ์‚ฌ์šฉํ•  ์ˆ˜๋„ ์žˆ๋‹ค.

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