[SpringBoot] @RequestParam, @PathVariable ์ฐจ์ด์ 

๋ฐ์ดํ„ฐ ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ์ฃผ๊ณ ๋ฐ›์„ ๋•Œ ์—ฌ๋Ÿฌ ๊ฐ€์ง€ ๋ฐฉ๋ฒ•์ด ์žˆ์ง€๋งŒ

์˜ค๋Š˜์€ @RequestParam๊ณผ @PathVariable์˜ ์ฐจ์ด์ ์— ๋Œ€ํ•ด์„œ ์•Œ์•„๋ณด๋ ค ํ•œ๋‹ค.

  1. http://restapi.com?userId=test&memo=ํ…Œ์ŠคํŠธ

  2. http://restapi.com/test/ํ…Œ์ŠคํŠธ

1๊ณผ ๊ฐ™์€ ๋ฐฉ์‹์€ ์ฟผ๋ฆฌ ์ŠคํŠธ๋ง์ด๋ผ ๋ถ€๋ฅด๋ฉฐ Get ๋ฐฉ์‹์˜ ํ†ต์‹ ์„ ํ•  ๋•Œ ์ฃผ๋กœ ์“ฐ์ธ๋‹ค.

2์™€ ๊ฐ™์€ ๋ฐฉ์‹์€ RESTful ๋ฐฉ์‹์ด๋ฉฐ Rest ํ†ต์‹ ํ•  ๋•Œ ์“ฐ์ธ๋‹ค.

๊ฐ์ž์˜ ์žฅ๋‹จ์ ์ด ์žˆ์œผ๋ฉฐ ๋‘ ๊ฐœ์˜ ๋ฐฉ์‹์€ Spring์—์„œ ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ๋ฐ›๋Š” ๋ฐฉ์‹์ด ์กฐ๊ธˆ ๋‹ค๋ฅด๋‹ค.

@RequestParam

@RestController
public class TestController (){

  @GetMapping("/")
  public String test(@RequestParam("userId") String userId,
                     @RequestParam("memo")   String memo){

    //์•„๋ž˜์™€ ๊ฐ™์ด ํ•ด๋‹น ๋ณ€์ˆ˜์— ํŒŒ๋ผ๋ฏธํ„ฐ๊ฐ’์ด ํ• ๋‹น๋œ๋‹ค.
    //userId = "test"
    //memo   = "ํ…Œ์ŠคํŠธ"

    return "TEST ์„ฑ๊ณต"
  }

}

@PathVariable

@RestController
public class TestController (){

  @GetMapping("/{userId}/{memo}")
  public String test(@PathVariable("userId") String userId,
                     @PathVariable("memo")   String memo){

    //์•„๋ž˜์™€ ๊ฐ™์ด ํ•ด๋‹น ๋ณ€์ˆ˜์— ํŒŒ๋ผ๋ฏธํ„ฐ๊ฐ’์ด ํ• ๋‹น๋œ๋‹ค.
    //userId = "test"
    //memo   = "ํ…Œ์ŠคํŠธ"

    return "TEST ์„ฑ๊ณต"
  }

}

@PathVariable์—์„œ ์ด๋ฉ”์ผ๊ณผ ๊ฐ™์€ ๋ฐฉ์‹์˜ ๊ฐ’์ด๋‚˜ ํŠน์ˆ˜๋ฌธ์ž๋ฅผ ๋ฐ›์„ ๋•Œ๋Š” ๊ฐ’์ด ์ž˜๋ฆฌ๊ฑฐ๋‚˜ ๋น„์ •์ƒ์ ์œผ๋กœ ๋“ค์–ด์˜จ๋‹ค.

์ด๋•Œ๋Š” ์•„๋ž˜์™€ ๊ฐ™์€ ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ•˜๋ฉด ์ •์ƒ์ ์œผ๋กœ ๋ฐ›์„ ์ˆ˜ ์žˆ๋‹ค.

@RestController
public class TestController (){

  @GetMapping("/{userId}/{memo:.+}")
  public String test(@PathVariable("userId") String userId,
                     @PathVariable("memo")   String memo){

    //์•„๋ž˜์™€ ๊ฐ™์ด ํ•ด๋‹น ๋ณ€์ˆ˜์— ํŒŒ๋ผ๋ฏธํ„ฐ๊ฐ’์ด ํ• ๋‹น๋œ๋‹ค.
    //userId = "test"
    //memo   = "ํ…Œ์ŠคํŠธ"

    return "TEST ์„ฑ๊ณต"
  }

}

@PathVariable์€ ์•„๋ฌด๋ž˜๋„ RESTful ๋ฐฉ์‹์— ๋งž๊ฒŒ ์ข€ ๋” ์ง๊ด€์ ์ด๋‹ค.

@RequestParam๋Š” null ๊ฐ’ ํ—ˆ์šฉ์ด๋‚˜ ํ‚ค:๋ฐธ๋ฅ˜ ๊ฐ’์œผ๋กœ ๋ณด๋‚ผ ์ˆ˜ ์žˆ๋‹ค๋Š” ์  ์ •๋„๋กœ ๋“ค ์ˆ˜ ์žˆ๋‹ค.

๊ผญ ์ •๋‹ต์€ ์—†์œผ๋‹ˆ ์ƒํ™ฉ์— ๋งž๊ฒŒ ์‚ฌ์šฉํ•˜๋ฉด ์ข‹์„ ๊ฑฐ ๊ฐ™๋‹ค.

๋‹ค๋ฅธ ๊ธ€ ์ฝ์–ด๋ณด๊ธฐ โฌ‡๏ธ